isPrototypeOf和Javascript中的instanceof有什么区别?

在我自己的一些旧代码中,我使用了以下内容:

Object.prototype.instanceOf = function( iface ) { return iface.prototype.isPrototypeOf( this ); }; 

然后我做(例如)

 [].instanceOf( Array ) 

这工作,但似乎下面会做同样的:

 [] instanceof Array 

现在,这当然只是一个非常简单的例子。 所以我的问题是:

a instanceof b 总是b.prototype.isPrototypeOf(a)吗?

是的,他们做同样的事情,都遍历原型链寻找一个特定的对象。

两者之间的区别在于它们是什么以及如何使用它们,例如isPrototypeOfObject.prototype对象上可用的函数 ,它允许您testing特定对象是否在另一个对象的原型链中,因为此方法已定义在Object.prototype ,它可用于所有对象。

instanceof一个运算符 ,它需要两个操作数,一个对象和一个构造函数 ,它将testing传递的函数prototype属性是否存在于对象链上(通过[[HasInstance]](V)内部操作,函数对象)。

例如:

 function A () { this.a = 1; } function B () { this.b = 2; } B.prototype = new A(); B.prototype.constructor = B; function C () { this.c = 3; } C.prototype = new B(); C.prototype.constructor = C; var c = new C(); // instanceof expects a constructor function c instanceof A; // true c instanceof B; // true c instanceof C; // true // isPrototypeOf, can be used on any object A.prototype.isPrototypeOf(c); // true B.prototype.isPrototypeOf(c); // true C.prototype.isPrototypeOf(c); // true 

运算符优先级和真实性有所不同,因为一个是expression式,另一个是方法调用。 有一件事要强调的是,无论是遍历原型链 ,所以你不能假设匹配的原型和所讨论的对象之间有一个一对一的映射:

 var i = 0; function foo() { console.log("foo"); console.log(i++ + ": " + Object.prototype.isPrototypeOf(Object) ) //true console.log(i++ + ": " + Function.prototype.isPrototypeOf(Function) ) //true console.log(i++ + ": " + Function.prototype.isPrototypeOf(Function) ) //true console.log(i++ + ": " + Function.prototype.isPrototypeOf(Object) ) //true console.log(i++ + ": " + RegExp.prototype.isPrototypeOf( RegExp(/foo/) ) ) //true console.log(i++ + ": " + Object.prototype.isPrototypeOf( RegExp(/foo/) ) ) //true console.log(i++ + ": " + Function.prototype.isPrototypeOf( RegExp(/foo/) ) ) //false console.log(i++ + ": " + Object.prototype.isPrototypeOf(Math) ) //true console.log(i++ + ": " + Math.isPrototypeOf(Math) ) //false } function bar() { console.log("bar"); console.log(i++ + ": " + (Object instanceof Object) ) //true console.log(i++ + ": " + (Function instanceof Function) ) //true console.log(i++ + ": " + (Function instanceof Object) ) //true console.log(i++ + ": " + (RegExp(/foo/) instanceof RegExp) ) //true console.log(i++ + ": " + (RegExp(/foo/) instanceof Object) ) //true console.log(i++ + ": " + (RegExp(/foo/) instanceof Function) ) //false console.log(i++ + ": " + (Math instanceof Object) ) //true console.log(i++ + ": " + (Math instanceof Math) ) //error } try { foo() } catch(e) { console.log(JSON.stringify(e)); } finally { try { bar(); } catch(e) { console.log(JSON.stringify(e)); } }