正确地给出下面的程序,控制台日志 - 注意链init
功能和return this
:的Object.create,链接和 '本'
const cat = {
init(sound) {
this.sound = sound;
return this;
},
makeSound() {
console.log(this.sound);
}
};
const fluffy = Object.create(cat).init('meeeaaaauuu');
fluffy.makeSound();
我的问题:如何以及为什么它工作所需要的return this
?下面看到它的错误删除:
const cat = {
init(sound) {
this.sound = sound;
// return this
},
makeSound() {
console.log(this.sound);
}
};
const fluffy = Object.create(cat).init('meeeaaaahuuu');
fluffy.makeSound();
MDN规定的Object.create返回新的对象,所以链接的init()应该工作......经过思考它... 是因为被链接的新对象仍然是“匿名”的?
注意,如果init()
都有自己的路线,因为我希望所有的作品,而无需return this
:
const fluffy = Object.create(cat);
fluffy.init('meeeaaaahuuu');
fluffy.makeSound();
你'init'方法什么都不返回。所以'const fluffy'等于'undefined'。它与'Object.create'无关。 – zerkms
哦 - 所以当链接一个不返回任何东西的方法时,原来的返回值(新的猫对象)会丢失?用init调用它时,const蓬松不等于新对象吗? – calipoop
不要把“链接”当作神奇或特殊的东西。如果可能的话,我甚至会依法禁止使用“链接”术语:人们出于某种原因将特殊属性赋予一个只返回某些东西的函数。 – zerkms