扩展运算符不会复制原型吗?
Does the spread operator not copy over the prototype?
以下代码似乎没有复制对象的原型。
const animalProto = {
eat() {
// function body
},
sleep() {
// function body
},
}
function animalCreator(proto, attributes) {
return {...Object.create(proto), ...attributes}
}
const cat = animalCreator(animalProto, { name: 'garfield' })
cat.eat() // this is an error; function is not defined; it doesn't appear to link the prototype chain.
如果我用以下内容替换点差,它会起作用:
return Object.assign(Object.create(proto), attributes)
基本上我的问题是为什么 Object.assign
有效但传播运算符无效。是否有 Object.assign
正在做的事情导致传播运算符丢失?
参见docs:
It copies own enumerable properties from a provided object onto a new object.
"Own enumerable"表示不包含原型上的属性。
如果您传播具有继承属性的对象(例如使用 Object.create
立即创建的对象),这些继承属性中的 none 将出现在结果中。
Object.assign
略有不同 - 它将第一个 右侧的所有属性分配给第一个 。如果你传递一个空对象作为第一个参数,它会更类似于传播:
return Object.assign({}, Object.create(proto), attributes)
在这种情况下,proto
中的任何内容都不会反映在输出中。
const proto = { foo: 'bar' };
const result = Object.assign({}, Object.create(proto), { another: 'prop' });
console.log(result);
Object.create()
创建一个新对象,该对象是原型 linked 到传递给它的对象。这意味着返回的对象没有得到父属性的副本,它只是有一个 link 到父原型。对象传播只复制对象自己的可枚举属性,不包括原型链上的属性。
const animalProto = {
eat() {
// function body
},
sleep() {
// function body
},
}
let o = Object.create(animalProto)
// o doesn't have it's own eat or sleep.
console.log(Object.getOwnPropertyNames(o))
console.log({...o}) // empty
以下代码似乎没有复制对象的原型。
const animalProto = {
eat() {
// function body
},
sleep() {
// function body
},
}
function animalCreator(proto, attributes) {
return {...Object.create(proto), ...attributes}
}
const cat = animalCreator(animalProto, { name: 'garfield' })
cat.eat() // this is an error; function is not defined; it doesn't appear to link the prototype chain.
如果我用以下内容替换点差,它会起作用:
return Object.assign(Object.create(proto), attributes)
基本上我的问题是为什么 Object.assign
有效但传播运算符无效。是否有 Object.assign
正在做的事情导致传播运算符丢失?
参见docs:
It copies own enumerable properties from a provided object onto a new object.
"Own enumerable"表示不包含原型上的属性。
如果您传播具有继承属性的对象(例如使用 Object.create
立即创建的对象),这些继承属性中的 none 将出现在结果中。
Object.assign
略有不同 - 它将第一个 右侧的所有属性分配给第一个 。如果你传递一个空对象作为第一个参数,它会更类似于传播:
return Object.assign({}, Object.create(proto), attributes)
在这种情况下,proto
中的任何内容都不会反映在输出中。
const proto = { foo: 'bar' };
const result = Object.assign({}, Object.create(proto), { another: 'prop' });
console.log(result);
Object.create()
创建一个新对象,该对象是原型 linked 到传递给它的对象。这意味着返回的对象没有得到父属性的副本,它只是有一个 link 到父原型。对象传播只复制对象自己的可枚举属性,不包括原型链上的属性。
const animalProto = {
eat() {
// function body
},
sleep() {
// function body
},
}
let o = Object.create(animalProto)
// o doesn't have it's own eat or sleep.
console.log(Object.getOwnPropertyNames(o))
console.log({...o}) // empty