【发布时间】:2012-12-09 18:12:51
【问题描述】:
问题:
- 为什么第一种方法能正确地将对象识别为法拉利? (在 Chrome 中测试)
- 我在这两种方法中的继承是否正确?
- 我是否正确理解第一个示例中有一些隐藏的“构造函数”属性,如果是,它们在哪里,是什么把它们放在那里?在我没有明确输入的第二个示例中是否有任何隐藏的构造函数属性?
- 如果我已经正确地完成了继承,我应该使用最后两种方法中的哪一种来让对象被识别为法拉利?还是我应该不在乎 - 毕竟“instanceof”仍然有效?
上下文:
使用 JavaScript 的“新”方法创建对象,效果很好:
Vehicle.prototype = {}; // Not required I know
function Vehicle() {
}
Car.prototype = new Vehicle();
function Car() {
}
Ferrari.prototype = new Car();
function Ferrari() {
}
var o = new Ferrari();
console.log(o);
哪些输出:
> Ferrari
> __proto__ : Car
> __proto__ : Vehicle
> __proto__ : Object <- The one that isn't required
> __proto__ : Object <- Provided by JS
...
hasOwnProperty: function hasOwnProperty() { [native code] }
...
现在我想做同样的事情,避免使用 new 关键字,这就是我所拥有的:
Vehicle.prototype = {};
function Vehicle() {
var vehicle = Object.create(Vehicle.prototype);
return vehicle;
}
Car.prototype = Vehicle();
Car.prototype.constructor = Vehicle;
function Car() {
var car = Object.create(Car.prototype);
return car;
}
Ferrari.prototype = Car();
Ferrari.prototype.constructor = Car;
function Ferrari() {
var ferrari = Object.create(Ferrari.prototype);
//ferrari.constructor = Ferrari; <- Lookey here - commented line
return ferrari;
}
var o = new Ferrari();
console.log(o);
哪些输出:
> **Car**
> __proto__ : Car
> constructor : function Car()
__proto__ : Vehicle
> constructor : function Vehicle()
__proto__ : Object <- The one that isn't required
> __proto__ : Object
...
hasOwnProperty: function hasOwnProperty() { [native code] }
...
请注意,输出的第一行现在是 Car,而不是 Ferrari。这可以通过删除注释行来纠正,或者通过改变法拉利的原型如下:
var realPrototype = Car();
realPrototype.constructor = Car;
Ferrari.prototype = Object.create(realPrototype);
Ferrari.prototype.constructor = Ferrari;
【问题讨论】:
-
您将
Ferrari.prototype.constructor设置为Car。但是重置constructor的重点是Ferrari的实例将其构造函数设置回Ferrari而不是Car(覆盖prototype时会自动发生)。 -
@pimvdb 我没有这样做的原因是因为在第二种方法中(在对象图中)法拉利的原型是法拉利,而实际上它是“实例一辆车”。有趣的是,当你对第一种方法做同样的事情时,它根本不会改变图表! - 不一致向我表明这不是正确的继承方式?
-
@Lee 这种继承方式很好,你只需要将每个子类型的构造函数设置为父类型。您可以省点麻烦并在函数体内执行此操作,也可以在每次为子类型制作原型时重置构造函数。看我的回答。还有,
o的原型是Ferrari,Ferrari的原型不是Ferrari
标签: javascript inheritance prototype