instanceof的内部机制

399 阅读1分钟

instanceof 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性。语法:object instanceof constructor 参数:object(要检测的对象.)constructor(某个构造函数) 描述:instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。

下面通过代码阐述instanceof的内部机制,假设现在有 x instanceof y 一条语句,则其内部实际做了如下判断:

function myInstanceof(x,y){
while(x.__proto__!==null){
	if(x.__proto__===y.prototype){
		return true;
	}
	x.__proto__= x.__proto__.__proto__
}
	return false

x会一直沿着隐式原型链__proto__向上查找直到x.__proto__.__proto__......===y.prototype为止,如果找到则返回true,也就是x为y的一个实例。否则返回false,x不是y的实例。

触类旁通

function F() {}function O() {}O.prototype = new F();var obj = new O();console.log(obj instanceof O); // trueconsole.log(obj instanceof F); // trueconsole.log(obj.__proto__ === O.prototype); // trueconsole.log(obj.__proto__.__proto__ === F.prototype); // true