代码之家  ›  专栏  ›  技术社区  ›  antichris

如何在javascript中创建可变长参数列表的函数包装器

  •  1
  • antichris  · 技术社区  · 15 年前

    其目的是构建一个包装器,以提供在各种脚本主机上以变量arity调用本机函数的一致方法,从而可以在浏览器中以及在windows脚本主机或其他脚本引擎中执行脚本。
    我知道三种方法各有缺点。

    1. eval() 方法:

      function wrapper () {
          var str = '';
          for (var i=0; i<arguments.lenght; i++)
              str += (str ?', ':'') + ',arguments['+i+']';
          return eval('[native_function] ('+str+')');
          }
      
    2. switch() 方法:

      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]);
              }
          }
      
    3. apply() 方法:

      function wrapper () {
          return [native_function].apply([native_function_namespace], arguments);
          }
      

    你问他们怎么了?

    1. 好吧,我们能不能深入研究一下 表达式() 是邪恶的吗?还有所有的字符串连接…不是一个被贴上“优雅”标签的解决方案。

    2. 永远不可能知道最大值 n 那么有多少 cases 准备。这也会使剧本的篇幅达到极大的程度,并对圣者造成罪恶。 干的 原理。

    3. 该脚本可以在不支持 应用程序() 方法。

    现在的问题是:还有别的解决办法吗?

    2 回复  |  直到 13 年前
        1
  •  3
  •   Peter Bailey    15 年前

    只使用 apply() . 为了你 过时的 执行引擎,就这么做

    if ( 'undefined' == typeof Function.prototype.apply )
    {
      Function.prototype.apply = function( context, args )
      {
        // whatever hacky way you want to implement it - i guess eval.
      }
    }
    
        2
  •  -1
  •   Sergey Glotov Nitesh Khosla    13 年前

    就像自动的“this”变量一样,有一个“arguments”变量保存传递给函数的所有参数。见 javascript variadic .

    推荐文章