Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript new object reference

Tags:

javascript

what is the correct syntax to create a new instance of the object as opposed to 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 them all. I know that javascript passes objects by reference, so I am assuming it's because they are all referring to the same object. I tried this but it is obviously wrong.

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

Thanks in advance.

like image 400
Praesagus Avatar asked Dec 10 '22 21:12

Praesagus


1 Answers

Do the following:

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 = ...
like image 96
cgp Avatar answered Dec 28 '22 01:12

cgp