我正在玩JavaScript类继承(我正在使用node.js)。我得到子类实例的“未定义”值。这是我的例子:
我定义了一个Squirrel类,我想在KillerSquirrel子类中专门化这个类。我想创建Squirrel和KillerSquirrel类的实例。
function Squirrel(name, color) {
this.name = name;
this.color = color;
console.log("A new " + this.color + " squirrel named " + this.name + " is born!!!");
};
// add a new method called speak()
Squirrel.prototype.speak = function(text) {
console.log(this.name + " squirrel says: '" + text + "'");
};
// specialize the Squirrel class by creating a new KillerSquirrel constructor
function KillerSquirrel(name, color) {
this.soul = 'very bad';
console.log("Bhrrr ... a new " + this.color + " killer squirrel named " + this.name + " is born!!!");
}
KillerSquirrel.prototype.__proto__ = Squirrel.prototype;
// add kill method
KillerSquirrel.prototype.kill = function(obj){
console.log(this.name + " squirrel killed " + obj.name + " squirrel");
}
// replace the speak() method
KillerSquirrel.prototype.speak = function(text) {
console.log(this.name + " squirrel says: 'Grhhh! " + text + "' Grhhh!");
};
var squirrel = new Squirrel("Gummy", "brown");
squirrel.speak("My name is " + squirrel.name);
var killer = new KillerSquirrel("Mr.Hide", "black");
killer.speak("My name is " + killer.name);
我使用它的构造函数创建一个Squirrel的Squirrel实例,并将一些值传递给构造函数,这可以按预期工作。当我尝试使用其构造函数创建子类KillerSquirrel的实例并将一些值传递给它时,杀手松鼠实例具有“未定义的属性”。
请参阅:
$ node killersquirrel.js
A new brown squirrel named Gummy is born!!!
Gummy squirrel says: 'My name is Gummy'
Bhrrr ... a new undefined killer squirrel named undefined is born!!!
undefined squirrel says: 'Grhhh! My name is undefined' Grhhh!
答案 0 :(得分:4)
子类构造函数应该通过特殊构造(apply或call)手动调用超类构造函数,如下所示:
function KillerSquirrel(name, color) {
Squirrel.apply(this, arguments);
this.soul = 'very bad';
console.log("Bhrrr ... a new " + this.color + " killer squirrel named " + this.name + " is born!!!");
}
或
function KillerSquirrel(name, color) {
Squirrel.call(this, name, color);
this.soul = 'very bad';
console.log("Bhrrr ... a new " + this.color + " killer squirrel named " + this.name + " is born!!!");
}
虽然对于这种情况(当参数相同时),第一种形式是首选。