// 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() {
this.name = "penguin";
this.numLegs = 2;
}
// set its prototype to be a new instance of Animal
var penguin = new Animal("Penguin", 2);
penguin.sayName();
编译器要求我“创建一个名为penguin的新企鹅实例”......
不确定我在这里做错了什么
答案 0 :(得分:1)
这里是如何在javascript中使用原型继承制作一个继承Animal的Penguin对象:
// 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() {
this.name = "penguin";
this.numLegs = 2;
}
// set its prototype to be a new instance of Animal
Penguin.prototype = new Animal();
// Create new Penguin
var penguin = new Penguin();
penguin.sayName(); // outputs "Hi my name is penguin"
var legCount = penguin.numLegs; // outputs 2
这是一篇详细解释JavaScript Prototypal Inheritance的文章: http://pietschsoft.com/post/2008/09/JavaScript-Prototypal-Inheritence-Explained-in-Simple-Terms