Praesagus
Praesagus

Reputation: 2104

Javascript new object reference

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.

Upvotes: 4

Views: 3828

Answers (3)

KooiInc
KooiInc

Reputation: 122936

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 don't need the new operator for a new instance of Item.

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

Upvotes: 3

Daniel Moura
Daniel Moura

Reputation: 7966

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

Upvotes: 2

cgp
cgp

Reputation: 41381

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 = ...

Upvotes: 9

Related Questions