js中prototype的陷阱

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>原型陷阱</title>
<meta name="description" content="">
<meta name="keywords" content="">
<style type="text/css">
</style>
</head>
<body>
<script type="text/javascript">
	//当我们对原型对象执行完全替换时,可能会触发原型链中某种异常
	//prototype.constructor属性是不可靠的
	function Dog(){
		this.tail=true;
	}
	var benji=new Dog();
	var rusty=new Dog();
	Dog.prototype.say=function(){
		return "Woof!";
	}
	benji.say();//Woof!
	rusty.say();//Woof!
	benji.constructor===Dog; //true
	rusty.constructor===Dog; //true
	//现在,我们用一个自定义的新对象完全覆盖掉原有的原型对象
	Dog.prototype={
		paws: 4,
		hair: true
	}
	//事实证明,这会使原有对象不能访问原型的新增属性,它们依然通过那个神秘的链接
	//与原有属性对象保持联系。
	typeof benji.paws; //undefined
	benji.say(); //Woof!
	typeof benji._proto_.say; //function
	typeof benji_proto_.paws; //undefined
	//而我们之后创建的所有对象使用的都是被更新后的prototype对象
	var lucy=new Dog();
	lucy.say(); //TypeError: lucy.say is not a function
	lucy.paws; //4
	//并且新的对象秘密链接_proto_也指向了新的prototype对象
	typeof lucy._proto_.say; //undefined
	typeof lucy._proto_.paws; //number
	//但这时候,新对象的constructor属性就不能再保持正确了,原本应该是Dog()的引用
	// 却指向了Object()
	lucy.constructor; // function Object(){[native code]}
	benji.constructor; //function Dog() {this.tail=true;}
	//当然,我们可以通过重新设置constructor属性来解决上述所有的异常行为:
	function Dog(){}
	Dog.prototype={};
	new Dog().constructor===Dog; //false
	Dog.prototype.constructor=Dog;
	new Dog().constructor===Dog; //true
	//当我们重写某对象的prototype时,需要重置相应的constructor属性

</script>
</body>
</html>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

啊哈前端

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值