ES6之拷贝对象

时间:2023-03-10 06:34:20
ES6之拷贝对象
function copyObject(orig) {
var copy = Object.create(Object.getPrototypeOf(orig));
//创建一个新的原型对象
copyOwnPropertiesFrom(copy, orig);
return
copy;
}
  
function copyOwnPropertiesFrom(target, source) {
Object
.getOwnPropertyNames(source) //获取对象所有属性名称
.forEach(function(propKey) {
var desc = Object.getOwnPropertyDescriptor(source, propKey);//获取属性的attribute对象
Object.defineProperty(target, propKey, desc); //通过attribute对象定义多个属性
});
return target;
}