【问题标题】:Prototypal Inheritance in Objects对象中的原型继承
【发布时间】: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 = [] 将直接在 speedylazy 对象上添加一个新的 stomach 属性。所以,在第二次,它不需要在原型链中查找并使用共享的hasmter.stomach属性
  • 对象对每个对象都有自己的属性胃是可以的,但是如果我有太多对象怎么办?在每个对象上添加相同的属性似乎不是一个好的解决方案
  • 这就是为什么您需要使用class 进行继承和创建新对象。不是对象字面量

标签: javascript


【解决方案1】:

问题来源:learn.javascript.ru 本站也提供了说明

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-06
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    • 2014-11-26
    相关资源
    最近更新 更多