splat over JavaScript 对象(带有新的)? [英] splat over JavaScript object (with new)?

查看:32
本文介绍了splat over JavaScript 对象(带有新的)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用 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);

这篇关于splat over JavaScript 对象(带有新的)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆