zoukankan      html  css  js  c++  java
  • JavaScript Patterns 3.3 Patterns for Enforcing new

    When your constructor has something like  this.member and you invoke the constructor without  new,  you’re  actually  creating  a  new  property  of  the  global  object  called member and accessible through window.member or simply member.

    // constructor
    
    function Waffle() {
    
        this.tastes = "yummy";
    
    }
    
    // a new object
    
    var good_morning = new Waffle();
    
    console.log(typeof good_morning); // "object"
    
    console.log(good_morning.tastes); // "yummy"
    
    // antipattern:
    
    // forgotten `new`
    
    var good_morning = Waffle();
    
    console.log(typeof good_morning); // "undefined"
    
    console.log(window.tastes); // "yummy" 

    This undesired behavior is addressed in ECMAScript 5, and in strict mode this  will no longer point to the global object. If ES5 is not available, there’s still something you can do to make sure that a constructor function always behaves like one even if called without new. 

    Naming Convention

    uppercase the first letter in constructor names (MyConstructor) and lowercase it in “normal” functions and methods (myFunction).

    Using that

    function Waffle() {
    
        var that = {};
    
        that.tastes = "yummy";
    
        return that;
    
    } 
    
    function Waffle() {
    
        return {
    
            tastes: "yummy"
    
        };
    
    } 
    
    var first = new Waffle(),
    
          second = Waffle();
    
    console.log(first.tastes); // "yummy"
    
    console.log(second.tastes); // "yummy"

    Disadvantage

    The link to the prototype is lost, so any members you add to the Waffle()prototype will not be available to the objects.

    Self-Invoking Constructor

    In the constructor you check whether this is an instance of your constructor, and if not, the constructor invokes itself again, this time properly with new: 

    function Waffle() {
    
        if (!(this instanceof Waffle)) {
            return new Waffle();
        }
    
        this.tastes = "yummy";
    }
    
    Waffle.prototype.wantAnother = true;
    
    // testing invocations
    
    var first = new Waffle(),
    
    second = Waffle();
    
    console.log(first.tastes); // "yummy"
    
    console.log(second.tastes); // "yummy"
    
    console.log(first.wantAnother); // true
    
    console.log(second.wantAnother); // true
  • 相关阅读:
    中缀表达式转换为后缀表达式
    看4S员工自爆!黑啊,太黑了
    解剖孩子晚上磨牙的6大原因
    2D 3D IMAX 电影座位选择
    蒸鸡蛋羹
    0010 4S店提车注意事项
    2012年北京市车船税基准税额
    火车票预订 电话 和 网站
    远程计算机关机方法
    win7 用户信息丢失
  • 原文地址:https://www.cnblogs.com/haokaibo/p/Patterns-for-Enforcing-new.html
Copyright © 2011-2022 走看看