【发布时间】:2016-04-16 07:17:18
【问题描述】:
我查看了这个 reference link 并最终使用了 Matthew 的解决方案,因为它对我有用。
var factory ={};
factory.Tree = function(arg1,arg2,arg3,arg4){
console.log(arg1+""+arg2+""+arg3+""+arg4);
}
function instantiate(classname){
return new (function(a){ return factory[classname].apply(this,a);})(Array.prototype.splice.call(arguments,1));
// also is this ^^^ a good practice? instead of declaring the temp function beforehand
// function t(a) {return factory[classname].apply(this,a);}
// return new t(Array.prototype.splice.call(arguments,1));
}
var newObj = instantiate("Tree",1,2,3,4); // this prints 1234 --> works
不过,我不确定为什么使用 user123444555621 的解决方案只有在我传入“参数”(即包括“类名”在内的所有内容)时才有效:
function instantiate(classname){
return new (Function.prototype.bind.apply(factory[classname], arguments));
}
var newObj = instantiate("Tree",1,2,3,4); // this prints 1234 --> works
但是如果我切片“arguments”并删除“classname”,然后传入结果数组,它就不会按预期工作:
function instantiate(classname){
var args = Array.prototype.splice.call(arguments,1);
// ^^ I checked and this prints 1,2,3,4 as well
return new (Function.prototype.bind.apply(factory[classname], args));
}
var newObj = instantiate("Tree",1,2,3,4); // this prints 234undefined
我不知道为什么,但不知何故,args 数组似乎(再次)被切片并删除了它的第一个元素(在本例中为 1)。
有人可以提供任何见解吗?谢谢
【问题讨论】:
标签: javascript class