假设我们有以下内容:
function Super() {
// init code
}
function Sub() {
Super.call(this);
// other init code
}
Sub.prototype = new Super();
var sub = new Sub();
然后,在我们的 ocde 的其他部分,我们可以使用以下任一方法来检查关系:
sub instanceof Super;
或
Super.prototype.isPrototypeOf( sub )
无论哪种方式,我们都需要拥有对象 (sub) 和父构造函数 (Super)。那么,有什么理由让您使用一个与另一个吗?有没有其他情况区分的更清楚?
我已经仔细阅读了2464426 , 但没有找到足够具体的答案。
最佳答案
假设您不在代码中使用构造函数,而是使用Object.create
生成具有特定原型(prototype)的对象。您的程序可能设计为根本不使用构造函数:
var superProto = {
// some super properties
}
var subProto = Object.create(superProto);
subProto.someProp = 5;
var sub = Object.create(subProto);
console.log(superProto.isPrototypeOf(sub)); // true
console.log(sub instanceof superProto); // TypeError
在这里,您没有用于instanceof
的构造函数。您只能使用 subProto.isPrototypeOf(sub)
。
关于JavaScript isPrototypeOf 与 instanceof 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18343545/