splat over JavaScript 对象(带有新的)?对象、splat、over、JavaScript

2023-09-06 18:44:39 作者:宠你一世

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

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

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

myArgs = [1,2];

使用 可以 我可以做到:

can.apply(this, myArgs);

尝试使用 foo 时:

new foo.apply(this, myArgs);

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

I get this error (because I'm calling 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);