There is no native method for cloning objects. Underscore implements [`_.clone`][1] which is a shallow clone.
_.clone = function(obj) {
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
It either slices it or extends it.
Here's [`_.extend`][2]
// extend the obj (first parameter)
_.extend = function(obj) {
// for each other parameter
each(slice.call(arguments, 1), function(source) {
// loop through all properties of the other objects
for (var prop in source) {
// if the property is not undefined then add it to the object.
if (source[prop] !== void 0) obj[prop] = source[prop];
}
});
// return the object (first parameter)
return obj;
};
Extend simply iterates through all the items and creates a new object with the items in it.
You can roll out your own naive implementation if you want
function clone(o) {
var ret = {};
Object.keys(o).forEach(function (val) {
ret[val] = o[val];
});
return ret;
}
There are good reasons to avoid deep cloning because closures cannot be cloned.
I've personally asked a question about [`deep cloning objects before`](
[To see links please register here]
) and the conclusion I came to is that you just don't do it.
My recommendation is use [`underscore`][3] and it's [`_.clone`][1] method for shallow clones
[1]:
[To see links please register here]
[2]:
[To see links please register here]
[3]:
[To see links please register here]