构造函数忘记new? 看这里看这里

方法一:自调用构造函数

 1 function Person(name){
 2     if( !(this instanceof Person)){//一定要放在开头。检查this是否为构造函数的一个实例
 3         return new Person(name);//自调用,会通通走一遍,不用担心后面的属性没加上
 4     }
 5     this.name = name;
 6     this.love = true;
 7 }
 8 Person.prototype.sayHello = function(){
 9     console.log('hi, '+ this.name);
10 }
11 
12 var per1 = new Person('wqh');
13 var per2 = Person('czm');
14 console.log(per1.name);//wqh
15 console.log(per1.love);//true
16 console.log(per2.name);//wqh
17 console.log(per2.love);//true
18 per1.sayHello();//hi, wqh
19 per2.sayHello();//hi, czm

 

方法二:使用that

 1 function Person(name){
 2     var that = Object.create(Person.prototype);//手工指定原型
 3     that.name = name;
 4      that.love = true;
 5     return that;//返回that
 6 }
 7 Person.prototype.sayHello = function(){
 8     console.log('hi, '+ this.name);
 9 }
10 
11 var per1 = Person('wqh');
12 var per2 = new Person('czm');
13 console.log(per1.name);//wqh
14 console.log(per1.love);//true
15 per1.sayHello();//hi, wqh
16 console.log(per2.name);//czm
17 console.log(per1.love);//true
18 per2.sayHello();//hi, czm

显然,我更倾向于第一种(*^__^*)

参考《javaScript模式》P47~P49,并稍作修改

 

posted @ 2017-01-02 16:07  奋发的小前端  阅读(257)  评论(0编辑  收藏  举报