splat over JavaScript 对象(新的)?

splat over JavaScript object (with new)?

如何在不使用 ECMA6 features 的情况下跨越对象?

尝试

function can(arg0, arg1) {
    return arg0 + arg1;
}

function foo(bar, haz) {
    this.bar = bar;
    this.haz = haz;
}

myArgs = [1,2];

有了can我可以做到:

can.apply(this, myArgs);

尝试 foo 时:

new foo.apply(this, myArgs);

我收到此错误(因为我正在调用 new):

TypeError: function apply() { [native code] } is not a constructor

使用Object.create

function foo(bar, haz) {
    this.bar = bar;
    this.haz = haz;
}

x = Object.create(foo.prototype);
myArgs = [5,6];
foo.apply(x, myArgs);

console.log(x.bar);

使用 Object.create(proto) 是解决此问题的正确方法。

Coco 和 LiveScript(Coffeescript 子集)提供了一种解决方法:

new foo ...args

编译为

(function(func, args, ctor) {
  ctor.prototype = func.prototype;
  var child = new ctor, result = func.apply(child, args), t;
  return (t = typeof result)  == "object" || t == "function" ? result || child : child;
  })
(foo, args, function(){});

在 CoffeeScript 中:

(function(func, args, ctor) {
  ctor.prototype = func.prototype;
  var child = new ctor, result = func.apply(child, args);
  return Object(result) === result ? result : child;
})(foo, args, function(){});

这些 hack 丑陋、缓慢且不完美;例如,Date 依赖于其内部 [[PrimitiveValue]]。参见 here