instanceof 和 prototype 关系

    一直想知道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执行结果如图

 

       

 

总结:

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

        A instanceof B

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

 

期待你们的意见,谢谢。 

 

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值