如上所述,Object.assign() 会进行浅层克隆,无法复制源对象的自定义方法,也无法复制带有enumerable: false 的属性。
保留方法和不可枚举的属性需要更多代码,但不会更多。
这将对数组或对象进行浅层克隆,复制源的方法和所有属性:
function shallowClone(src) {
let dest = (src instanceof Array) ? [] : {};
// duplicate prototypes of the source
Object.setPrototypeOf(dest, Object.getPrototypeOf(src));
Object.getOwnPropertyNames(src).forEach(name => {
const descriptor = Object.getOwnPropertyDescriptor(src, name);
Object.defineProperty(dest, name, descriptor);
});
return dest;
}
例子:
class Custom extends Object {
myCustom() {}
}
const source = new Custom();
source.foo = "this is foo";
Object.defineProperty(source, "nonEnum", {
value: "do not enumerate",
enumerable: false
});
Object.defineProperty(source, "nonWrite", {
value: "do not write",
writable: false
});
Object.defineProperty(source, "nonConfig", {
value: "do not config",
configurable: false
});
let clone = shallowClone(source);
console.log("source.nonEnum:",source.nonEnum);
// source.nonEnum: "do not enumerate"
console.log("clone.nonEnum:", clone.nonEnum);
// clone.nonEnum: – "do not enumerate"
console.log("typeof source.myCustom:", typeof source.myCustom);
// typeof source.myCustom: – "function"
console.log("typeof clone.myCustom:", typeof clone.myCustom);
// typeof clone.myCustom: – "function"
jsfiddle