[size=medium;]一种简洁的原型模式:[/size]
[size=medium;]1、[/size][size=medium;] 使用简洁的原型模式时,constructor属性不在指向person函数,其原因是override默认的原型模式。新的原型模式的constructor会默认指向object函数[/size].
[size=medium;]2、 从写整个原型函数后[/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]
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]