JavaScript多级继承和isPrototypeOf

时间:2015-05-21 06:20:00

标签: javascript inheritance multi-level

我在JavaScript中实现了多级继承,如下所示

function MovingObject(){

}

function Vehicle(){

}
Vehicle.prototype = Object.create(MovingObject);

function Car(){

}
Car.prototype = Object.create(Vehicle);

var c = new Car();

汽车是车辆的孩子,而车辆又是MovingObject的孩子,所以我期待Car成为MovingObject的间接孩子。

下面的语句返回true表示Car是Vehicle的直接子项

Vehicle.isPrototypeOf(c);

但是,下面的语句不会返回true

MovingObject.isPrototypeOf(c);

任何想法为什么它不会返回真实如何让它返回真实

1 个答案:

答案 0 :(得分:1)

这是关于JavaScript的常见问题。

MovingObjectVehicle构造函数,但它们不是原型。

也就是说,您应该使用Object.create(ConstructorFunction.prototype)而不仅仅是ConstructorFunction

在JavaScript中,即使函数也是一个对象,这就是为什么Object.create(...)在提供构造函数时起作用的原因。生成的对象将构造函数对象作为原型。

实际上,您既可以使用Object.create(ConstructorFunction.prototype)方法,也可以使用new实现相同的目标:

Vehicle.prototype = new MovingObject();

new方法的主要问题是您使用构造函数创建新对象,并且您可能正在向原型中添加不需要的数据和行为:



function MovingObject() {
  this.x = 11;
}

function Vehicle() {}
Vehicle.prototype = new MovingObject();

var instance = Object.create(Vehicle.prototype);

// What? instance has "x" property!!
document.getElementById("result").textContent = instance.x;

<div id="result"></div>
&#13;
&#13;
&#13;

更新

OP在一些评论中表示:

  

这是否意味着我们无法建立真正的is-a关系   Car和MovingObject在这里?如果是,我们如何使用代码进行测试?   意思是,我想只在Car是一个移动对象时执行一些代码。   我怎样才能完成测试?

检查并执行以下代码段以使其更清晰:

&#13;
&#13;
function A() {}

function B() {}
B.prototype = Object.create(A.prototype);

function C() {}
C.prototype = Object.create(B.prototype);

var instanceOfB = Object.create(B.prototype);
var instanceOfC = Object.create(C.prototype);

var result1 = A.prototype.isPrototypeOf(instanceOfC);
var result2 = B.prototype.isPrototypeOf(instanceOfC);
var result3 = A.prototype.isPrototypeOf(instanceOfB);

document.getElementById("result1").textContent = result1;
document.getElementById("result2").textContent = result2;
document.getElementById("result3").textContent = result3;
&#13;
<h2>instanceOfC is prototype of A?</h2>
<div id="result1"></div>
<h2>instanceOfC is prototype of B?</h2>
<div id="result2"></div>
<h2>instanceOfB is prototype of A?</h2>
<div id="result3"></div>
&#13;
&#13;
&#13;

更新2

正如@RobertRossmann对这个答案进行了评论,可以使用instanceof运算符实现相同的代码片段,该运算符具有有效的附加值,可以检查实例是否是提供构造函数的某些原型: / p>

&#13;
&#13;
function A() {}

function B() {}
B.prototype = Object.create(A.prototype);

function C() {}
C.prototype = Object.create(B.prototype);

var instanceOfB = Object.create(B.prototype);
var instanceOfC = Object.create(C.prototype);

var result1 = instanceOfC instanceof B;
var result2 = instanceOfC instanceof C;
var result3 = instanceOfB instanceof A;

document.getElementById("result1").textContent = result1;
document.getElementById("result2").textContent = result2;
document.getElementById("result3").textContent = result3;
&#13;
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>
&#13;
&#13;
&#13;