简体   繁体   English

javascript从类继承

[英]javascript inherit from a class

Im learning inheritance. 我正在学习继承。 In the code below 在下面的代码中

1)penguin inherits from Animal 1)企鹅继承自动物

2)when I call penguin.sayName(); 2)当我打电话给penguin.sayName(); why does it output "Hi my name is undefined"; 为什么输出“嗨,我的名字未定义”;

function Animal(name,numLegs){
    this.name = name;
    this.numLegs = numLegs;


}
Animal.prototype.sayName = function(){
  console.log("Hi my name is " + this.name);
};


function Penguin(){}

Penguin.prototype = new Animal();

var penguin = new Penguin("Captain Cook", 2);
penguin.sayName();

You need to add the name and numLegs properties to the penguin object via the function constructor. 您需要通过函数构造函数将namenumLegs属性添加到penguin对象。 These two properties are specific to the Animal object and will not be assigned simply by calling the Penguin constructor. 这两个属性特定于Animal对象,不会简单地通过调用Penguin构造函数来分配。

function Penguin(name,numLegs){
  this.name = name;
  this.numLegs = numLegs.
}

Working Example: http://jsfiddle.net/5A7hH/ 工作示例: http : //jsfiddle.net/5A7hH/

You could also use the constructor on the prototype chain, which is similar to calls of the super() constructor in Java. 您还可以在原型链上使用构造函数,这类似于Java中对super()构造函数的调用。

function Penguin(name,numLegs){
   this.constructor(name,numLegs);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM