【发布时间】:2022-07-27 23:41:25
【问题描述】:
我有一个仓鼠对象,如果我对其中任何一个调用eat,它会从其中继承两只仓鼠,它会写入两只仓鼠。
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]; 来工作
【问题讨论】:
-
正确的继承方式是:
let speedy = Object.create(hamster)。即使那样,它也会有相同的行为。如果stomach属性不直接存在于对象上,它将检查它的 [[Prototype]],即hasmter对象,并且由hasmter派生的所有对象都将具有相同的stomach属性。this.stomach = []将直接在speedy和lazy对象上添加一个新的stomach属性。所以,在第二次,它不需要在原型链中查找并使用共享的hasmter.stomach属性 -
对象对每个对象都有自己的属性胃是可以的,但是如果我有太多对象怎么办?在每个对象上添加相同的属性似乎不是一个好的解决方案
-
这就是为什么您需要使用
class进行继承和创建新对象。不是对象字面量
标签: javascript