正確地給出下面的程序,控制檯日誌 - 注意鏈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