V
V
Valenso2013-12-19 21:21:43
JavaScript
Valenso, 2013-12-19 21:21:43

How to create 2 identical independent objects in JavaScript?

Faced the following problem - I create 2 objects. I change properties in one object - they change in another. How to make them independent, even if they are based on the same set of initial data?

function Item(coordinates){
    this.coordinates = coordinates || false;

    this.moveItemToAValueBelow = function(value){
        for (var i in this.coordinates){
            this.coordinates[i][1]+=value;
        }
    }
}

var first = new Item(data);
var second = new Item(data);
second.moveItemToAValueBelow(20);

console.log(first.coordinates);
console.log(second.coordinates);

console.log shows the same thing. What is the correct way to create 2 different objects with the same data?
The full page code is presented here https://github.com/valenso/pattern

Answer the question

In order to leave comments, you need to log in

3 answer(s)
_
_ _, 2013-12-20
@Valenso

You should have started with what kind of data you have. I looked at github - you have nested arrays.
In this case, @ghaiklor's option wo n't work because it's only for flat objects.
data.slice(0) won't work either, because only the first level of the array will be unique.
Try JSON.parse(JSON.stringify(data))

_
_ _, 2013-12-19
@AMar4enko

Your objects are independent, but you pass the same data instance to the constructors, i.e. you have coordinates one for two objects.
JavaScript does not have a standard method for doing "deep cloning".
If you're using jQuery, you can try this.coordinates = $.extend({},coordinates).

E
Eugene Obrezkov, 2013-12-19
@ghaiklor

Or write your own clone() in pure JS

function clone(obj) {
    if (null == obj || "object" != typeof obj) return obj;
    var copy = obj.constructor();
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
    }
    return copy;
}

this.coordinates = clone(coordinates);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question