4

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
4

2 に答える 2

4

使用する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);
于 2015-01-25T01:33:19.640 に答える
0

を使用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その internal に依存してい[[PrimitiveValue]]ます。ここを参照してください。

于 2015-01-25T01:39:43.877 に答える