Javascript variable scope and links

I am trying to understand this javascript variable referring to the problem. Here is a fiddle to demonstrate what I'm going to explain: http://jsfiddle.net/XpVb5/1/

I have an object that I want to define and call within the individual properties of the object.

var vals = {'something':1};  //original object
var buf  = {'field1': vals, 'field2': vals};  //second object with original object used as properties

Now I want to change the property somethingonly field1, so I would do this:

buf.field1.something = 0;

However, this property will also change the property field2 something. I assume this is due to the way Javascript refers to variables in the process of defining a variable. But in any case, how can I get around this without explicitly calling {'something':0}every time I need to use it in the definition of a property; So:

var buf = {'field1': {'something':0}, 'field2': {'something':1}};
+4
source share
2 answers

Can be changed $valsto a function that returns an object. Each return will be a different instance.

var $vals = function(){
    return {"something":1}
}
var  buf     = {"field1": $vals(), "field2": $vals()};

//change the 'something' field for one of the buf properties
buf.field1.something = 0;

//see if the 'something' field changed for the other buf property
alert( buf.field2.something );

DEMO

+1
source

You need to create a copy of the vals object. Currently, you simply provide a link to an object in both places. When you modify the base object, the change appears in both buf (field1 + field2) because they provide only a reference to the base object.

Note. I am using JSON.parse (JSON.stringify ($ vals)) as a quick example of how to copy the $ vals object.

var $vals   = {"something":1},
    buf     = {"field1": JSON.parse(JSON.stringify($vals)), "field2": JSON.parse(JSON.stringify($vals))};

//change the 'something' field for one of the buf properties
buf.field1.something = 0;

//see if the 'something' field changed for the other buf property
alert( buf.field2.something );

http://jsfiddle.net/XpVb5/2/

gives

1

: " "

+3

All Articles