Clone/copy
Use ES5 to clone/copy objects
by Stefano
HTML
<a href="https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object">An answer to a SO question</a>
JavaScript
var c = { p:1,
e: "what",
b: {
f: function(x) {
console.log(x);
}
}
}
var c2 = Object.assign({}, c);
c2.e = "how";
console.log("c = ", c);
console.log("c2 = ", c2);
// c.b.f = 'c';
c2.b.f('ciao');
console.log(c.prototype === c2.prototype);
if (!Object.assign) {
Object.defineProperty(Object, 'assign', {
enumerable: false,
configurable: true,
writable: true,
value: function(target) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert first argument to object');
}
var to = Object(target);
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource === undefined || nextSource === null) {
continue;
}
nextSource = Object(nextSource);
var keysArray = Object.keys(nextSource);
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable) {
to[nextKey] = nextSource[nextKey];
}
}
}
return to;
}
});
}