我正在学习 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
原型(prototype)设置为 Animal
的新实例时是正确的。然而,当我提交代码时,我收到一条错误消息“确保创建一个名为 penguin 的新 Penguin 实例!”
最佳答案
使用此代码:
var penguin = {
name: "Pinguino"
};
您只需创建一个 Object 类的对象。
要创建 Penguin
类型的企鹅,实例化 Penguin
类:
var penguin = new Penguin("Pinguino");
penguin.sayName();
关于javascript - 尝试让一个新的JS类继承原类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26245289/