instanceof 和 prototype 关系

努力的zhiyi 2013-02-23

    一直想知道js的 instanceof 是根据什么来判断两个对象的继承关系? 会不会跟prototype有关,然后就试试了

    如果觉得下面的代码比较长,请先看注释

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>intanceof.html</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  </head>
  <body>
    <script type="text/javascript">
    	/*
    		A instanceof B 
    		如果A.__proto__ === B.prototype 则返回true
    	*/
    	var proto = {
    		say:function(){
    			alert("my name is "+this.name);
    		}
    	}
    	var Parent = function(name){
    		this.name = name||"yan";
    	}
    	Parent.prototype = proto;
    	
    	var Child = function(age){
    		this.age = age;
    	}
    	Child.prototype = proto;
    	var child = new Child(11);
	var parent = new Parent();
//测试    	
    	console.group("instanceof是根据prototype来判断两个对象的继承关系");
    	console.log("parent instanceof Parent :"+(parent instanceof Parent));//true;
    	console.log("child instanceof Parent :"+(child instanceof Parent));//true;
    	console.log("parent instanceof Child :"+(parent instanceof Child));//true;
    	console.log("Child instanceof Parent :"+(Child instanceof Parent));//false;
    	console.groupEnd();
/*
    		A instanceof B 
    		沿着A的原型链查找 如果有一个原型和B.prototype相等 则返回true 
    			如:A.__proto__.__proto__ === B.prototype 则返回true
    	*/
    	var Fn = function(){}
    	Fn.prototype = new Parent("a");
    	Child.prototype = new Fn();
    	var fn = new Fn();
    	child = new Child();
console.group("沿着原型链查找 如A instanceof B ,沿着A原型链查找直到找到跟B.prototype相等的原型");
    	console.log("child instanceof Parent :"+(child instanceof Parent));//true;
    	console.log("child instanceof Fn :"+(child instanceof Fn));//true;
    	console.log("fn instanceof Parent :"+(fn instanceof Parent));//true;
    	console.log("fn instanceof Child :"+(fn instanceof Child));//false;
    	console.groupEnd();
/*
    		进一步确定 instanceof 是检查原型的引用 而不是深入原型去检测他们的内容是否一样
    	*/
    	var proto2 = {
    		say:function(){
    			alert("my name is "+this.name);
    		}
    	}
    	Child = function(){}
    	Child.prototype = proto2;
    	child = new Child();
console.group(" instanceof 是检查原型的引用 而不是深入比较原型的内容");
    	console.log("child instanceof Parent :"+(child instanceof Parent));//false;
    	console.groupEnd();
</script>
  </body>
</html>

 firefox执行结果如图

        instanceof 和 prototype 关系

总结:

        js的instanceof是根据prototype来判断两个对象是否存在继承关系,

        A instanceof B

        js会沿着A的原型链查找 直到找到A.__proto__ === B.prototype 返回true

期待你们的意见,谢谢。 

注:__proto__属性指向prototype对象,对开发者不可见,例如var a = new A(), a.__proto__ = A.prototype;

相关推荐