[英]how to parse the json object with a function taking splat arguments in javascript?
[英]splat over JavaScript object (with new)?
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]]
。 看這里 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.