This is another way to create a javascript object (using object literal notation instead of function):
user = {
name: "Foo",
email: "[email protected]"
}
Is there a way to clone this object or is it a singleton?
This is another way to create a javascript object (using object literal notation instead of function):
user = {
name: "Foo",
email: "[email protected]"
}
Is there a way to clone this object or is it a singleton?
Most of the javascript frameworks have good support for object cloning.
var a= {'key':'value'};
var b= jQuery.extend( true, {}, a );
You can use JSON object (present in modern browsers):
var user = {name: "Foo", email: "[email protected]" }
var user2 = JSON.parse(JSON.stringify(user))
user2.name = "Bar";
alert(user.name + " " + user2.name); // Foo Bar
See in jsfiddle.
EDIT
If you need this in older browsers, see http://www.json.org/js.html.
I like to use this:
if (typeof Object.create !== 'function') {
Object.create = function (o) {
var F = function () {};
F.prototype = o;
return new F();
};
}
then any object I want to clone can be done as:
user = {
name: "Foo",
email: "[email protected]"
};
var user2 = Object.create(user);
As shown in (or similar to) JavaScript The Good Parts
Updated:
Object.prototype.clone = function clone(a) {
a=a||this;
var b = {};
for(var p in a) {
if(typeof(a[p])==="object"){b[p]=clone(a[p]);}
else {b[p]=a[p];}
}
return b;
};
var foo = {
name: "Foo"
, email: "[email protected]"
, obj: {a:"A",b:"B"}
}
var bar = foo.clone();
bar.name = "Bar";
bar.obj.b = "C";
console.dir(foo);
console.dir(bar);
Try this:
var clone = (function(){
return function (obj) { Clone.prototype=obj; return new Clone() };
function Clone(){}
}());
Here's what's going on.
__proto__.The cloned object will share all the properties of the original object without any copies of anything being made. If properties of the cloned object are assigned new values, they won't interfere with the original object. And no tampering of built-ins is required.
Keep in mind that an object property of the newly-created object will refer to the same object as the eponymous property of the cloned object. Assigning a new value to a property of the clone won't interfere with the original, but assigning values to the clone's object properties will.
Try this in chrome or firebug console:
var user = {
name: "Foo",
email: "[email protected]"
}
var clonedUser = clone(user);
console.dir(clonedUser);
A detailed explanation of this cloning technique can be found here.