• 构造函数忘记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中的equals和hashCode方法详解
    java集合(一)
    volatile和synchronized实现内存可见性的区别
    动态代理的原理
    过滤器的使用
    pageBean的实体类
    FindUserByPageServlet
    用户信息系统_serviceImpl
  • 原文地址:https://www.cnblogs.com/redking-fighting/p/6242595.html
Copyright © 2020-2023  润新知