【发布时间】:2015-05-21 06:19:59
【问题描述】:
我有一个用 JavaScript 实现的多级继承,如下所示
function MovingObject(){
}
function Vehicle(){
}
Vehicle.prototype = Object.create(MovingObject);
function Car(){
}
Car.prototype = Object.create(Vehicle);
var c = new Car();
Car 是 Vehicle 的子代,而 Vehicle 又是 MovingObject 的子代,所以我希望 Car 是 MovingObject 的间接子代。
以下语句返回 true,表明 Car 是 Vehicle 的直接子代
Vehicle.isPrototypeOf(c);
但是,下面的语句不返回 true
MovingObject.isPrototypeOf(c);
知道为什么它不返回 true,以及如何让它返回 true?
【问题讨论】:
-
应该是
Vehicle.prototype = Object.create(MovingObject.prototype),和其他一样。 -
即使使用 Vehicle.prototype = Object.create(MovingObject.prototype),我该如何编写代码来测试 Car 和 MovingObject 实例之间的关系?
标签: javascript inheritance multi-level