在尝试理解 javascript 构造函数时,我一直在查看 this question .
在我看来,我理解它是合理的,但是,讽刺的是,当我尝试运行类似的代码时,它对我来说根本不起作用。
这是我的代码
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 is undefined”。
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(“我的 super 汽车”) 调用按照我预期的方式运行(将名称设置为“我的 super 汽车”)?
最佳答案
您不应该真正创建 Car
实例作为原型(prototype),而只创建一个继承自 Car.prototype
的对象。详情参见What is the reason to use the 'new' keyword at Derived.prototype = new Base 。相反,使用
SuperCar.prototype = Object.create(Car.prototype);
<小时/>
您的问题是您的 SuperCar 是由空函数创建的 - 它返回一个没有任何属性的对象。然而,它们继承自new Car()
,其name
是undefined
。这发生在你的 fiddle 中,因为函数声明(以function
关键字开头,查看 this explanation )被提升(在范围内的任何地方都可用)并被行覆盖
SuperCar = function () { };
这样您的 SuperCar
构造函数就不再调用 Car
构造函数。 Fixed fiddle
关于带参数的 JavaScript 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12660971/