首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对象中的原型继承

对象中的原型继承
EN

Stack Overflow用户
提问于 2022-07-27 15:29:18
回答 1查看 49关注 0票数 1

我有一个仓鼠对象,两只仓鼠继承,如果我叫他们吃,它写给两只仓鼠。

代码语言:javascript
复制
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

但是通过搜索,我找到了下面代码解决问题的解决方案。但是不知道发生了什么,原型遗传在这里是如何工作的。

代码语言:javascript
复制
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];来实现的。

EN

回答 1

Stack Overflow用户

发布于 2022-07-27 16:28:55

prototype链上的MDN页面解释了这些问题。在第一个代码中,stomach不存在于speedy中,因此编译器搜索原型链。

代码的一个有用的方面是在一次给所有后代喂食hamster。没有原型链涉及,因为hamster已经有一个胃。

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73140729

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档