How to work with Javascript objects? [duplicate]

0

I have two objects, objeto1 and objeto2 , and I want to assign all values from objeto1 to objeto2 , but when I use objeto2 = objeto1 and change some value of objeto2 objeto1 is also changed because they have the same address. How to create a new object with the same values in a quick way?

    
asked by anonymous 18.05.2015 / 14:58

1 answer

0
var objeto1 = new Object();
var objeto2 = new Object();

// objeto1 = objeto2 funciona como apontamento
// quando é nova instancia de objeto então tem que instanciar e não referenciar

If cloned object is already filled:

    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;
}

var d1 = new Date();

/* Wait for 5 seconds. */
var start = (new Date()).getTime();
while ((new Date()).getTime() - start < 5000);


var d2 = clone(d1);
alert("d1 = " + d1.toString() + "\nd2 = " + d2.toString());

link

    
18.05.2015 / 15:00