【问题标题】:Problems inheriting properties from a supertype从超类型继承属性的问题
【发布时间】:2020-11-16 21:07:12
【问题描述】:

我正在创建一个 Animal 超类型构造函数,该构造函数的方法应该适用于所有“鸟”和“猫”对象。

  • 我应该如何添加此原型以确保不会覆盖子类型的原型?
  • 我可以在超类型原型中使用子类型原型的变量吗?

示例

function Animal() { }

Animal.prototype = {
  constructor: Animal,
  say: function(sound) {
    console.log(`${sound}`);
  }
};

function Cat(name) {
  this.name=name
 }
function Bird(name) {
  this.name=name
 }
Cat.prototype = {
  constructor:Bird,
  sound:'meow'
}
Bird.prototype = {
  constructor:Bird,
  sound:'Bach Op1 D minor'
}

Cat.prototype = Object.create(Animal.prototype)
Bird.prototype = Object.create(Animal.prototype)
//is this overwriting the prototype already set?
let myCat = new Cat("rupert")
console.log(myCat.name, myCat.say(), Cat.prototype)

【问题讨论】:

  • 您是否有理由使用此语法而不是 classes
  • 刚开始玩,发现一些知识差距,就到了这里。事实上,类似乎更容易和更易读@Thomas

标签: javascript inheritance prototype


【解决方案1】:

您可以使用Object.assign 继承 Animal 的原型,也可以添加自己的字段和方法。另外,您需要使用this.sound 来访问实例本身的属性。

Animal.prototype = {
  constructor: Animal,
  say: function() {
    console.log(`${this.sound}`);
  }
};
//...
Cat.prototype = Object.assign(Object.create(Animal.prototype), {
  constructor:Bird,
  sound:'meow'
});
Bird.prototype = Object.assign(Object.create(Animal.prototype),{
  constructor:Bird,
  sound:'Bach Op1 D minor'
});

演示:

function Animal() { }

Animal.prototype = {
  constructor: Animal,
  say: function() {
    console.log(`${this.sound}`);
  }
};

function Cat(name) {
  this.name=name
 }
function Bird(name) {
  this.name=name
 }
Cat.prototype = Object.assign(Object.create(Animal.prototype), {
  constructor:Bird,
  sound:'meow'
});
Bird.prototype = Object.assign(Object.create(Animal.prototype),{
  constructor:Bird,
  sound:'Bach Op1 D minor'
});
//is this overwriting the prototype already set?
let myCat = new Cat("rupert")
console.log(myCat.name, myCat.say(), Cat.prototype)

【讨论】:

  • 太棒了。但在代码中,对“say”的调用仍然返回undefined
  • @misternobody 你没有从函数中返回任何东西。你只是在调用console.log,这就是它隐式返回undefined的原因。
  • 呃?我在这里很困惑,我相信无论如何应该有一些声音输出
  • @misternobody 然后写return this.sound 而不是console.log(this.sound)
  • 哦,对不起,我没有看到第一行的喵字。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
  • 2014-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多