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

后端 未结 30 2711
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:08

    See also how CoffeeScript does it.

    s = new Something([a,b,c]...)

    becomes:

    var s;
    s = (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args);
      return Object(result) === result ? result : child;
    })(Something, [a, b, c], function(){});
    

提交回复
热议问题