Question

I call a property in object, when I update this one, the property is update too.

http://jsfiddle.net/zw8Ag/3/

object = 
{
    path : [1,2,3,4],
    test: function() 
    {
        var destination = this.path;
        destination[3] = 99;
    } 
}

this.path[3] return 99

What's the right way to get the data, not the reference ?

Was it helpful?

Solution 2

Because when you have an object in a variable, the variable doesn't contain object's data. Instead, it contains a reference to object's data in memory.

Then, var destination = this.path; just copies the reference, not the data. And if you modify one of the variables, both will be affected.

If you want to copy object's data, you can use

function extend(obj, props) {
    for(var i in props) if(props.hasOwnProperty(i))
        obj[i] = props[i];
}
var copy = extend({}, obj);

Or you can also try inheritance:

var copy = Object.create(obj);

Or in this case, since it's an array, better use slice:

var copy = arr.slice();

OTHER TIPS

Because it's assigning the reference not passing the value.

To clone the array: var destination = this.path.slice(0);

Demo: http://jsfiddle.net/8Pvj5/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top