Link to a new Javascript object

What is the correct syntax for creating a new instance of an object, rather than a pointer to the original? Here is my example:

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

when I set the value of oInputs[oTitle].element for any oTitle , it sets the value of all of them. I know that javascript passes objects by reference, so I assume this because they all refer to the same object. I tried this, but this is clearly wrong.

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

Thanks in advance.

+4
source share
3 answers

Follow these steps:

 function OItem() { this.colIndex = 0; } var oInputs = { Qty: new OItem(), Tare: new OItem(), Rate: new OItem(), Total: new OItem() }; 

and then set your properties:

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

This is another way to create a constructor:

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

Now you do not need a new operator for a new instance of the element.

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

All Articles