我有一个仓鼠对象,两只仓鼠继承,如果我叫他们吃,它写给两只仓鼠。
let hamster = {
stomach: [],
eat(food) {
this.stomach.push(food);
}
};
let speedy = {
__proto__: hamster
};
let lazy = {
__proto__: hamster
};
// This one found the food
speedy.eat("apple");
console.log( speedy.stomach ); // apple
// This one also has it, why?
console.log( lazy.stomach ); // apple
但是通过搜索,我找到了下面代码解决问题的解决方案。但是不知道发生了什么,原型遗传在这里是如何工作的。
let hamster = {
stomach: [],
eat(food) {
// assign to this.stomach instead of this.stomach.push
this.stomach = [food];
}
};
let speedy = {
__proto__: hamster
};
let lazy = {
__proto__: hamster
};
// Speedy one found the food
speedy.eat("apple");
console.log( speedy.stomach ); // apple
// Lazy one's stomach is empty
console.log( lazy.stomach ); // <nothing>
上面的例子似乎是通过用this.stomach.push(food);替换this.stomach = [food];来实现的。
发布于 2022-07-27 16:28:55
prototype链上的MDN页面解释了这些问题。在第一个代码中,stomach不存在于speedy中,因此编译器搜索原型链。
代码的一个有用的方面是在一次给所有后代喂食hamster。没有原型链涉及,因为hamster已经有一个胃。
let hamster = {
stomach: [],
eat(food) {
// assign with spread operator to this.stomach instead of this.stomach.push
this.stomach=[...this.stomach,food];
}
};
let speedy = {
__proto__: hamster
};
let lazy = {
__proto__: hamster
};
// Feed the 'hamster'
hamster.eat("apple");
console.log( speedy.stomach ); // apple
console.log( lazy.stomach ); // apple
hamster.eat("carrot");
console.log( speedy.stomach ); // apple, carrot
console.log( lazy.stomach ); // apple, carrot
https://stackoverflow.com/questions/73140729
复制相似问题