zoukankan      html  css  js  c++  java
  • 构造函数忘记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,并稍作修改

  • 相关阅读:
    【递归】拆分自然数
    HDOJ3068最长回文
    博弈论——尼姆博奕
    vijos P1047最小公倍数
    Eular质数筛法-hiho一下 第九十三周
    hdoj-5652 India and China Origins二分+bfs
    hdoj-1166排兵布阵 简单的树状数组
    hdoj-5641 king's phone
    hdoj-1548简单的bfs题目
    命令中"|"的意义
  • 原文地址:https://www.cnblogs.com/redking-fighting/p/6242595.html
Copyright © 2011-2022 走看看