在尝试理解 javascript 构造函数时,我一直在研究这个问题。
在我看来,我理解它是合理的,但具有讽刺意味的是,当我尝试运行类似的代码时,它根本不适合我。
这是我的代码
function Car(name) {
this.Name = name;
this.Year = 1999;
}
Car.prototype.Drive = function() {
document.write("My name is '" + this.Name + "' and my year is '" + this.Year + "'. <br />");
};
SuperCar = function () { };
SuperCar.prototype = new Car();
function SuperCar(name) {
Car.call(this, name);
}
var MyCar = new Car("mycar");
var MySuperCar = new SuperCar("my super car");
MyCar.Drive();
MySuperCar.Drive();
首先,这条线
SuperCar = function () { };
是它运行所必需的。如果我忽略它,我会在这一行出现错误“SuperCar 未定义”。
SuperCar.prototype = new Car();
我真的不明白为什么将 SuperCar 声明为空函数是必要的。
其次,当我运行代码时,我得到了这个结果
My name is 'mycar' and my year is '1999'.
My name is 'undefined' and my year is '1999'.
显然,对于 MySuperCar,从不调用 SuperCar(name) 函数,但 Car() 是。
添加此行无济于事
SuperCar.prototype.constructor = SuperCar;
这也不
SuperCar.prototype.constructor = function(name) {
Car.call(this, name);
};
(我一直在 IE 9 和 Chrome 22 上的脚本标签内运行代码)
我应该如何正确定义采用名称参数的 SuperCar 构造函数?或者,换一种说法,我怎样才能使新的 SuperCar("my super car") 调用按我预期的方式运行(将名称设置为“my super car”)?