用 forEach 来复制一个对象的副本
用 forEach 来复制一个对象的副本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| function copy(obj) { var copy = Object.create(Object.getPrototypeOf(obj)); var propNames = Object.getOwnPropertyNames(obj);
propNames.forEach(function(name) { var desc = Object.getOwnPropertyDescriptor(obj, name); Object.defineProperty(copy, name, desc); });
return copy; }
var copyObj1 = { a: 1, b: 2 }; var copyObj2 = copy(copyObj1); console.log(copyObj2); console.log(copyObj2 === copyObj1);
|
Object.create
Object.create(proto[, propertiesObject])
方法创建一个新对象,使用现有的对象来提供新创建的对象的proto
Object.getPrototypeOf
Object.getOwnPropertyNames
Object.getOwnPropertyDescriptor
Object.defineProperty
总结
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| function copy(obj) { var copy = Object.create(Object.getPrototypeOf(obj)); var propNames = Object.getOwnPropertyNames(obj);
propNames.forEach(function(name) { var desc = Object.getOwnPropertyDescriptor(obj, name); Object.defineProperty(copy, name, desc); });
return copy; }
|
资料