• 构造函数忘记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,并稍作修改

  • 相关阅读:
    线程同步的几种实现方案
    关于java中三种初始化块的执行顺序
    java数组
    Codeblocks 17汉化
    聚焦天狗
    linux下搭建svn添加多个仓库(项目)
    使用Python在windows环境下获取Linux服务器的磁盘、内存等信息
    python smtplib使用163发送邮件 报错 554 DT:SPM
    防抖与节流
    js
  • 原文地址:https://www.cnblogs.com/redking-fighting/p/6242595.html
Copyright © 2020-2023  润新知