javascript - 访问从 child 那里继承的功能

标签 javascript inheritance

第一段代码:

function Animal() {}
Animal.prototype.eat = function() {
  console.log("nom nom nom");
};

function Dog() {}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype = {
  constructor: Dog,
  bark: function() {
    console.log("Woof!");
  }
};
let beagle = new Dog();
console.clear();
beagle.eat(); // Should print "nom nom nom" but displays a error that eat 
//is not a function.
beagle.bark();

第二个代码:

function Animal() {}
Animal.prototype.eat = function() {
  console.log("nom nom nom");
};

function Dog() {}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
  console.log("Woof!");
}
let beagle = new Dog();
console.clear();
beagle.eat(); // Prints "nom nom nom"
beagle.bark(); // Prints "Woof!"

beagle.eat() 没有显示正确输出的第一个代码片段有什么问题。

最佳答案

您首先将 Dog 的原型(prototype)分配为 Object.create(Animal.prototype);,但随后在下一行您完全重新分配 Dog 的原型(prototype)为其他东西,因此继承链不再存在。调整您的第一个代码,您可能只想分配给 Dog.prototype 一次,并使用 Object.assignObject.create:

function Animal() {}
Animal.prototype.eat = function() {
  console.log("nom nom nom");
};

function Dog() {}
Dog.prototype = Object.assign(
  Object.create(Animal.prototype),
  {
    constructor: Dog,
    bark: function() {
      console.log("Woof!");
    }
  }
);
let beagle = new Dog();
beagle.eat();

关于javascript - 访问从 child 那里继承的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50826748/

相关文章:

javascript - 需要在 JQuery cookie 中保存 'this' 值

javascript - 使用 Canvas ,我得到一个空白屏幕,试图用阴影打印标题 1 和标题 2

c# - Client Generated 不向第三方提供有关已知类型的信息

generics - Kotlin 泛型继承

javascript - 警报返回为未定义

php - 使用jquery提交表单后隐藏div?

javascript - 如何从值列表中获取键?

python - 如何在python中继承 "Manager().list"?

具有泛型和继承的 java 抽象类 : Bound mismatch

c++ - 使用模板和继承时出现问题,错误x86_64体系结构的 undefined symbol :