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,并稍作修改

  • 相关阅读:
    一个禁止某个document element对象选中文本的js方法
    LNMP中nginx和php的安装流程
    nginx编译
    nginx服务器管理
    nginx+phpfpm配置文件的组织结构
    win 8 x64 english key
    WdatePicker 设置时间范围在某个时间段
    Vm workstation安装win8 的问题
    android 开发中xml的解析
    多线程下载文件
  • 原文地址:https://www.cnblogs.com/redking-fighting/p/6242595.html
Copyright © 2011-2022 走看看