试图获得一个新的JS类来继承原来的类'方法

Trying to get a new JS class to inherit original class' method

本文关键字:JS 继承 方法 原来 一个      更新时间:2023-09-26

我正在学习一个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实例!"

使用此代码:

var penguin = {
    name: "Pinguino"
};

您只需创建一个object类的对象。要创建Penguin类型的企鹅,安装Penguin类:

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

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

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;

有关构造函数函数和原型的更多信息,请点击此处。