Is JavaScript's “new” keyword considered harmful?

前端 未结 12 2200
情书的邮戳
情书的邮戳 2020-11-21 23:18

In another question, a user pointed out that the new keyword was dangerous to use and proposed a solution to object creation that did not use new.

12条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-21 23:29

    I wrote a post on how to mitigate the problem of calling a constructor without the new keyword.
    It's mostly didactic, but it shows how you can create constructors that work with or without new and doesn't require you to add boilerplate code to test this in every constructor.

    http://js-bits.blogspot.com/2010/08/constructors-without-using-new.html

    Here's the gist of the technique:

    /**
     * Wraps the passed in constructor so it works with
     * or without the new keyword
     * @param {Function} realCtor The constructor function.
     *    Note that this is going to be wrapped
     *    and should not be used directly 
     */
    function ctor(realCtor){
      // This is going to be the actual constructor
      return function wrapperCtor(){
        var obj; // object that will be created
        if (this instanceof wrapperCtor) {
          // Called with new
          obj = this;
        } else {
          // Called without new. Create an empty object of the
          // correct type without running that constructor
          surrogateCtor.prototype = wrapperCtor.prototype;
          obj = new surrogateCtor();
        }
        // Call the real constructor function
        realCtor.apply(obj, arguments);
        return obj;
      }
    
      function surrogateCtor() {}
    }
    

    Here's how to use it:

    // Create our point constructor
    Point = ctor(function(x,y){
      this.x = x;
      this.y = y;
    });
    
    // This is good
    var pt = new Point(20,30);
    // This is OK also
    var pt2 = Point(20,30);
    

提交回复
热议问题