0

在尝试理解 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”)?

4

2 回答 2

4

您不应该真正创建一个实例Car作为原型,而只创建一个继承自Car.prototype. 有关详细信息,请参阅在 Derived.prototype = new Base 中使用“new”关键字的原因是什么。相反,使用

SuperCar.prototype = Object.create(Car.prototype);

您的问题是您SuperCar的 s 是由空函数创建的 - 它返回一个没有任何属性的对象。然而,它们继承自new Car(), who nameis undefined。这发生在您的小提琴中,因为函数声明(以关键字开头function,请查看此说明)被提升(在范围内的任何地方都可用)并被该行覆盖

SuperCar = function () { };

这样您的SuperCar构造函数就不会再调用Car构造函数了。固定小提琴

于 2012-09-30T11:54:10.010 回答
2

您不需要空函数。你创建了一个空SuperCar函数,然后设置了它的原型,然后用的定义重写了它SuperCar

function SuperCar() {}
SuperCar.prototype = new Car();

function SuperCar() {} // original SuperCar overwritten
于 2012-09-30T11:44:06.367 回答