var与function,这对常量和方法更好

这是一个nodejs应用程序,也可能成为一个Chrome打包的应用程序。 以下哪一个更适合在应用程序中设置常量和方法?

// HARDWARE SETTINGS AND SCALING FACTORS \\ function GPIO8() { this.sensorType = "I/O board"; this.name = "XYZ Co. 8 Channel USB GPIO Module"; this.info = "GPIO, 10 bit, 0-5V ADC (Analog to Digital Converter)"; this.voltSupply = 5.15; // Measure with multimeter and set this constant. this.vMin = 0; // lowest output voltage. this.vMax = 1023; // highest output voltage. (10bit = 2^10) this.scalingFactor = function ( ) { return this.voltSupply / (this.vMax - this.vMin); }; this.voltScaled = function (adcReading) { return parseFloat(adcReading, 10) * this.scalingFactor(); }; } 

或这个?

 // HARDWARE SETTINGS AND SCALING FACTORS \\ var GPIO8 = { sensorType : "I/O board", name : "XYZ Co. 8 Channel USB GPIO Module", info : "GPIO, 10 bit, 0-5V ADC (Analog to Digital Converter)", voltSupply : 5.15, // Measure with multimeter and set this constant. vMin : 0, // lowest output voltage. vMax : 1023, // highest output voltage (10bit = 2^10) scalingFactor : function ( ) { return this.voltSupply / (this.vMax - this.vMin); }, voltScaled : function (adcReading) { return parseFloat(adcReading, 10) * this.scalingFactor(); } } 

两者都在应用程序中工作。 我们有10个不同的硬件设置每个不同的范围,比例因子和方法。 其他硬件每个都有几个常量。 以上是最简单的。 在我设置其他9之前,我想正确地开始。

我读到它们都是对象,而var和function并不重要。 我不是一个亲js编码器。 哪一个是这个特定用法的首选方法? (太主观了吗?)

其次,scalingFactor()和voltScaled(…)更适合于这些对象内的方法,或作为对象之外的单独函数。 (我希望我能得到正确的术语。)

如果要创build同一types的多个对象,该函数更方便。 这是经典的面向对象。 如果要使用多个GPIO8对象,可以调用new GPIO8(/* some specific settings */) ,然后使用在所有GPIO8对象中通用的各种方法设置对象的原型。

然而,在你的情况下,它看起来像GPIO8将是唯一的types,因此,字面对象符号(你显示的第二个例子)可能是好的。

如果我是你,我可能会花一些时间研究JavaScript的inheritance,即Object.prototype 。 那么你可以决定GPIO8是否属于另一个class级等

TL; DR:如果您需要类似对象的“工厂”,函数符号将会很有帮助