Use of .apply() with 'new' operator. Is this possible?

后端 未结 30 3402
Happy的楠姐
Happy的楠姐 2020-11-22 00:39

In JavaScript, I want to create an object instance (via the new operator), but pass an arbitrary number of arguments to the constructor. Is this possible?

30条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 01:02

    This constructor approach works both with and without the new keyword:

    function Something(foo, bar){
      if (!(this instanceof Something)){
        var obj = Object.create(Something.prototype);
        return Something.apply(obj, arguments);
      }
      this.foo = foo;
      this.bar = bar;
      return this;
    }
    

    It assumes support for Object.create but you could always polyfill that if you're supporting older browsers. See the support table on MDN here.

    Here's a JSBin to see it in action with console output.

提交回复
热议问题