Objects in Javascript "Assign" -
i have object
var person1{ name : "john", lastname : "doe" } and did assignment this
person2 = person1; but if this:
person1.name = "mike"; then person2.name "mike"
i'm trying make person2 "independent".
going on? "referencing objects" ?
you're right. referencing situation. there no cloning going on when assign object variable, program creates new reference person1 called person2
you have use dedicated cloning function, depending on if using pure js or framework jquery.
here pure js solution (source http://heyjavascript.com/4-creative-ways-to-clone-objects/):
function cloneobject(obj) { if (obj === null || typeof obj !== 'object') { return obj; } var temp = obj.constructor(); // give temp original obj's constructor (var key in obj) { temp[key] = cloneobject(obj[key]); } return temp; } var person2 = cloneobject(person1);
Comments
Post a Comment