splat over JavaScript 对象(带有 new)

splat over JavaScript object (with new)?

本文关键字:带有 new 对象 over JavaScript splat      更新时间:2023-09-26

如何在不使用 ECMA6 功能的情况下跨对象进行拼接?

尝试

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(){});

这些黑客丑陋、缓慢且不完美; 例如,Date依赖于其内部[[PrimitiveValue]]。看这里。