2009-04-24 106 views
4

与指向原始对象的指针相比,创建对象的新实例的正确语法是什么?这是我的例子:Javascript new object reference

var oItem = { element: null, colIndex: 0 }; 
var oInputs = { Qty: oItem, Tare: oItem, Rate: oItem, Total: oItem }; 
for (var oTitle in oInputs) { 
    oInputs[oTitle].element = ... 

时,我对任何oTitle设置oInputs[oTitle].element值它设置他们全部的价值。我知道JavaScript通过引用传递对象,所以我假设这是因为它们都指的是同一个对象。我尝试过,但显然是错误的。

var oInputs = { Qty: new oItem, Tare: new oItem, Rate: new oItem, Total: new oItem }; 

在此先感谢。

回答

9

执行以下操作:

function OItem() { 
    this.colIndex = 0; 
} 

var oInputs = { Qty: new OItem(), Tare: new OItem(), Rate: new OItem(), Total: new OItem() }; 

,然后设置你的属性:

for (var oTitle in oInputs) { 
    oInputs[oTitle].element = ... 
+0

你能举个例子吗?谢谢 – Praesagus 2009-04-24 20:49:58

+0

完美,谢谢。 :) – Praesagus 2009-04-24 20:56:24

2
function oItem() { 
this.element= null; 
this.colIndex= 0; 
} 
var oInputs = { Qty: new oItem(), Tare: new oItem(), Rate: new oItem(), Total: new oItem() }; 
+1

不错,但我会坚持使用大写第一个字母的惯例来表示原型或对象构造函数。 – cgp 2009-04-24 20:56:22

3

这是另一种方式来创建一个构造函数:

function Item(element,colIndex){ 
    if (this instanceof Item){ 
     this.element = element || null; 
     this.colIndex = colIndex || 0; 
    } else { 
     return new Item(element,colIndex); 
    } 
} 

现在你不对于新的Item实例,不需要新的操作符。

var oInputs = { Qty: Item(), 
       Tare: Item(), 
       Rate: Item(), 
       Total: Item() }; 
相关问题