试图让一个新的JS类继承原始类的方法

时间:2014-10-07 21:06:29

标签: javascript object inheritance

我正在阅读JavaScript教程,并要求我创建以下内容:

Create a Penguin object with the variable name penguin and any name you'd like.

Then call penguin.sayName();.

我的代码如下:

// the original Animal class and sayName method
function Animal(name, numLegs) {
    this.name = name;
    this.numLegs = numLegs;
}
Animal.prototype.sayName = function() {
    console.log("Hi my name is " + this.name);
};

// define a Penguin class
function Penguin(name) {
    this.name = name;
    this.numLegs = 2;
};

// set its prototype to be a new instance of Animal
Penguin.prototype = new Animal();

// Here's where I need to create the Penguin object
var penguin = {
    name: "Pinguino"
};

penguin.sayName(name);

我非常确定我的代码是正确的,直到我将Penguin原型设置为Animal的新实例。但是,当我提交代码时,我收到错误消息"确保创建一个名为penguin的新Penguin实例!"

2 个答案:

答案 0 :(得分:1)

使用此代码:

var penguin = {
    name: "Pinguino"
};

您只需创建类 Object 的对象。 要创建Penguin类型的企鹅, instanciate Penguin类:

var penguin = new Penguin("Pinguino");
penguin.sayName();

答案 1 :(得分:0)

以下是对代码的一些改进:

function Penguin(name) {
// do not copy paste re use your code
// but actually re use it by calling 
// the parent constructor
  Animal.call(this,name,2);
//    this.name = name;
//    this.numLegs = 2;
};

// set its prototype to be a new instance of Animal
// Do not create an instance of Parent to set the 
// prototype part of inheritance
//Penguin.prototype = new Animal();
Penguin.prototype = Object.create(Animal.prototype);
//when overwriting prototype you will have prototype.constructor
// point to the wrong function, repair that
Penguin.prototype.constructor=Penguin;

有关构造函数和原型here的更多信息。