以下代码似乎没有复制到对象原型上。
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.
Run Code Online (Sandbox Code Playgroud)
如果我将散布替换为以下内容,它将起作用:
return Object.assign(Object.create(proto), attributes)
Run Code Online (Sandbox Code Playgroud)
从本质上来说,我的问题是为什么Object.assign可以工作,而散布运算符却不能。是否有Object.assign正在执行的操作,表明传播运算符丢失了?
见文档:
它将自己的可枚举属性从提供的对象复制到新对象。
“自己可枚举”表示将不包含原型上的属性。
如果您散布具有继承属性的对象(例如使用立即创建的对象Object.create),则结果中将不包含那些继承属性。
Object.assign略有不同-将所有属性分配给第一个到第一个的右侧。如果您传递了一个空对象作为第一个参数,则它与传播更相似:
return Object.assign({}, Object.create(proto), attributes)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,任何内容proto都不会反映在输出中。
return Object.assign({}, Object.create(proto), attributes)
Run Code Online (Sandbox Code Playgroud)
Object.create()创建一个新对象,该对象的原型链接到传递给它的对象。这意味着返回的对象不会获得父级属性的副本,它只具有到父级原型的链接。对象扩展仅复制对象自己的可枚举属性,不包括原型链上的那些属性。
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}) // emptyRun Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
359 次 |
| 最近记录: |