1. 程式人生 > >面向對象-構造函數-優化-方案1

面向對象-構造函數-優化-方案1

對象 style ont code new blog var cnblogs spa



 1  //優化前
 2     function Person (name,age){
 3         this.name=name;
 4         this.age=age;
 5         this.run=function () {
 6             console.log(‘pao‘);
 7         }
 8     }
 9     var p=new Person(‘sz‘,18);
10     var p2=new Person(‘zs‘,19);
11     console.log(p.run == p2.run);//返回false
12
//優化後 13 var runfuctin=function () { 14 console.log(‘pao‘); 15 } 16 17 function Person (name,age){ 18 this.name=name; 19 this.age=age; 20 this.run=runfuctin; 21 } 22 var p=new Person(‘sz‘,18); 23 var p2=new Person(‘zs‘,19); 24 console.log(p.run == p2.run);//
返回true

 

面向對象-構造函數-優化-方案1