JavaScript中原型模式2

[size=medium;]一种简洁的原型模式:[/size]
                function person(){}		person.prototype={				name:"zhangsan",				age:33,				sayhello:function(){					alert("hello,i'm "+this.name);				}		}		var person = new person();		person.sayhello();  //hello,i'm zhangsan 		alert(person instanceof object);//true		alert(person instanceof person);//true		alert(person.constructor ==person);//false		alert(person.constructor==object);//true
 <img src="http://dl.iteye.com/upload/attachment/543666/437a95f9-964c-3eef-be4e-6685931a3ba6.png" alt="">
[size=medium;]1、[/size][size=medium;] 使用简洁的原型模式时,constructor属性不在指向person函数,其原因是override默认的原型模式。新的原型模式的constructor会默认指向object函数[/size].
[size=medium;]2、    从写整个原型函数后[/size]
function person(){}		var person = new person();		person.prototype={				name:"zhangsan",				age:33,				sayhello:function(){					alert("hello,i'm "+this.name);				}		}		person.sayhello();  //报错person.sayhello is not a function
 
function person(){}		person.prototype={				name:"zhangsan",				age:33,				sayhello:function(){					alert("hello,i'm "+this.name);				}		}		var person = new person();		person.sayhello();  //hello,i'm zhangsan
[size=medium;] 上面的两段代码:不同之处仅在于构建person实例的位置不同,却出现的不同的结果,我们可以用图来解释其真相。[/size]
<img src="http://dl.iteye.com/upload/attachment/543668/bbb6cd92-1de0-30cb-bba8-e6adaa94fab6.png" alt="">
[size=medium;]第一段报错代码的图解[/size]
<img src="http://dl.iteye.com/upload/attachment/543670/394d415b-3c78-35da-8e57-7c2da7063805.png" alt="" width="560" height="307">
[size=medium;]第二段代码的图解[/size]
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值