关于instanceof的深入认识

如果刚认识这个操作符,有个肤浅的理解

a instanceof b 只要在a的原型链上有b就返回true。这个理解其实是错的。

直到我重新读了一下《javascript高级程序设计》的6.3节 173页。

function inheritPrototype(subType, superType){
	var prototype = Object(superType.prototype);
	prototype.constructor = subType;
	subType.prototype = prototype;
}
function SuperType(name){
	this.name = name;
	this.colors  = ["red","blue","green"];
}
SuperType.prototype.sayName = function(){
	alert(this.name);
}
function SubType(name,age){
	SuperType.call(this, name);
	this.age = age;
}
inheritPrototype(SubType,SuperType);
SubType.prototype.sayAge = function(){
	alert(this.age);
}
var instance = new SubType("jie",29)

instance instanceof SubType //true 这个没有异议吧

instance instanceof SuperType //true 这个就比较奇怪了

如果console.log(instance);是看不到SuperType出现在instance的原型链上面的。

于是我上百度谷歌了一下:

a instanceof b底层的运算机制关键点如下:

1 b的数据类型必须为[object Function],否则就抛TypeError;

2 若a为Primitive Value则直接返回false, 若a的数据类型为Object则执行后续运算;

3 当且仅当b.prototype位于a的prototype chain中时,才返回true(由于Object.prototype.__proto__为null,因此prototype chain是有限链表);

所以正确的说法是   a instanceof b 只要在a的原型链上有等于b的原型就返回true

发表评论