![](/img/trans.png)
[英]What's the difference between isPrototypeOf and instanceof in Javascript?
[英]JavaScript isPrototypeOf vs instanceof usage
假设我们有以下内容:
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
生成具有特定原型的对象。 您的程序可能被架构为根本不使用构造函数:
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)
。
使用构造函数时,它几乎没有什么区别。 也许, instanceof
有点干净。 但是当你不......时:
var human = {mortal: true}
var socrates = Object.create(human);
human.isPrototypeOf(socrates); //=> true
socrates instanceof human; //=> ERROR!
所以isPrototypeOf
更通用。
根据MDN Ref :
isPrototypeOf()
与instanceof
运算符不同。 在表达式object instanceof AFunction
,对象原型链将针对AFunction.prototype
进行检查,而不是针对AFunction
本身。
var neuesArray = Object.create(Array);
Array.isPrototypeOf(neuesArray); // true
neuesArray instanceof Array // false
neuesArray instanceof Object // true
Array.isArray(neuesArray); // false
Array.prototype.isPrototypeOf(neuesArray); // false
Object.prototype.isPrototypeOf(neuesArray); // true
你了解我的朋友:) - 很简单
只是补充@ apsillers的答案
object instanceof constructor
var superProto = {}
// subProto.__proto__.__proto__ === superProto
var subProto = Object.create(superProto);
subProto.someProp = 5;
// sub.__proto__.__proto__ === subProto
var sub = Object.create(subProto);
console.log(superProto.isPrototypeOf(sub)); // true
console.log(sub instanceof superProto); // TypeError: Right-hand side of 'instanceof' is not callable
// helper utility to see if `o1` is
// related to (delegates to) `o2`
function isRelatedTo(o1, o2) {
function F(){}
F.prototype = o2;
// ensure the right-hand side of 'instanceof' is callable
return o1 instanceof F;
}
isRelatedTo( b, a );
TypeError:'instanceof'的右侧不可调用
instanceof
需要右侧值可调用,这意味着它必须是一个函数(MDN将其称为构造函数)
和instanceof
测试对象原型链中constructor.prototype
的存在。
但isPrototypeOf()
没有这样的限制。 当instanceof
检查superProto.prototype
, isPrototypeOf()
直接检查superProto
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.