//The following function performs such a copy:
function copyObject(orig) {
// 1. copy has same prototype as orig
var copy = Object.create(Object.getPrototypeOf(orig));
// 2. copy has all of orig’s properties
copyOwnPropertiesFrom(copy, orig);
return copy;
}
//The properties are copied from orig to copy via this function:
function copyOwnPropertiesFrom(target, source) {
Object.getOwnPropertyNames(source) // (1)
.forEach(function(propKey) { // (2)
var desc = Object.getOwnPropertyDescriptor(source, propKey); // (3)
Object.defineProperty(target, propKey, desc); // (4)
});
return target;
};
To create an identical copy of an object, you need to get two things right:
1. The copy must have the same prototype (see “Layer 2: The Prototype Relationship
Between Objects” on page 211) as the original.
2. The copy must have the same properties, with the same attributes as the original.
1. The copy must have the same prototype (see “Layer 2: The Prototype Relationship
Between Objects” on page 211) as the original.
2. The copy must have the same properties, with the same attributes as the original.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.