如何在不使用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
答案 0 :(得分: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);
答案 1 :(得分: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
依赖于其内部[[PrimitiveValue]]
。请参阅here。