目的是构建一个包装器,以提供在各种脚本主机上调用具有可变数量的本机函数的一致方法 - 以便脚本可以在浏览器以及 Windows 脚本主机或其他脚本引擎中执行。
我知道 3 种方法,每种方法都有其自身的缺点。
-
eval()
方法:
函数包装器 () {
var str = '';
for (var i=0; i
-
switch()
方法:
函数包装器 () {
开关(参数.长度){
案例0:
返回[native_function](参数[0]);
休息;
案例1:
返回[native_function](参数[0],参数[1]);
休息;
...
案例编号:
返回[native_function](参数[0],参数[1],...参数[n]);
}
}
-
apply()
方法:
函数包装器 () {
return [native_function].apply([native_function_namespace], 参数);
}
你问它们有什么问题吗?
-
那么,我们是否应该深入研究一下 eval()
邪恶的所有原因?还有所有的字符串连接......这不是一个可以被标记为“优雅”的解决方案。
-
人们永远无法知道最大n
,因此无法知道要准备多少案例
。这也会将脚本拉伸到巨大的比例,并违反神圣的DRY原则。
-
该脚本可以在不支持 apply()
方法的旧版(JavaScript 1.3 / ECMA-262-3 之前)引擎上执行。
现在的问题是:还有其他解决方案吗?
The intention is to build a wrapper to provide a consistent method of calling native functions with variable arity on various script hosts - so that the script could be executed in a browser as well as in the Windows Script Host or other script engines.
I am aware of 3 methods of which each one has its own drawbacks.
-
eval()
method:
function wrapper () {
var str = '';
for (var i=0; i<arguments.lenght; i++)
str += (str ?', ':'') + ',arguments['+i+']';
return eval('[native_function] ('+str+')');
}
-
switch()
method:
function wrapper () {
switch (arguments.lenght) {
case 0:
return [native_function] (arguments[0]);
break;
case 1:
return [native_function] (arguments[0], arguments[1]);
break;
...
case n:
return [native_function] (arguments[0], arguments[1], ... arguments[n]);
}
}
-
apply()
method:
function wrapper () {
return [native_function].apply([native_function_namespace], arguments);
}
What's wrong with them you ask?
-
Well, shall we delve into all the reasons why eval()
is evil? And also all the string concatenation... Not a solution to be labeled "elegant".
-
One can never know the maximum n
and thus how many cases
to prepare. This also would strech the script to immense proportions and sin against the holy DRY principle.
-
The script could get executed on older (pre- JavaScript 1.3 / ECMA-262-3) engines that don't support the apply()
method.
Now the question part: is there any another solution out there?
发布评论
评论(2)
只需使用
apply()
即可。对于您的过时的执行引擎,只需这样做Just use
apply()
. And for your antiquated execution engines, just do this就像自动的“this”变量一样,有一个“arguments”变量保存传递给函数的所有参数。请参阅 javascript 变量。
Just like the automatic 'this' variable, there is an 'arguments' variable that holds all the arguments passed in to the function. See javascript variadic.