理解JavaScript中的instanceof
instanceof原理
我们先写这样一个例子
function Girl(){}
Girl.prototype = {}
function Boy(){}
Boy.prototype ={}
var boy1 = new Boy();
alert(boy1 instanceof Boy);//true
alert(boy1 instanceof Object);//true
Boy.prototype = Girl.prototype;
alert(boy1 instanceof Boy);//false
alert(boy1 instanceof Girl);//false
alert(boy1 instanceof Object);//true;
var boy2= new Boy();
alert(boy2 instanceof Boy);//true
alert(boy2 instanceof Girl);//true
alert(boy2 instanceof Object);//true
Boy.prototype = null;
var boy3 = new Boy();
alert(boy3 instanceof Girl);//false
alert(boy3 instanceof Object);//true
alert(boy3 instanceof Boy);//error
结论:
instanceof 检测一个对象A是不是另一个对象B的实例的原理是:查看对象B的prototype指向的对象是否在对象A的[[prototype]]链上。如果在,则返回true,如果不在则返回false。不过有一个特殊的情况,当对象B的prototype为null将会报错(类似于空指针异常)。