javascript - 通过另一个函数透明地传递一个函数的参数

标签 javascript inheritance casting

我正在构建一个由数百个函数组成的相当大的 JavaScript 库。每个函数都有一定数量的参数,有时在设计时不知道。我需要通过某种参数 cleanUp() 函数传递每个函数参数。我可以做这样的事情:

function myFunction(param1, param2, ..., paramN) {
  var param1 = cleanUp(param1);
  var param2 = cleanUp(param2);
  ...
  var paramN = cleanUp(paramN);

  // Function's implementation goes here
}

function cleanUp(param) {
  // Cleanup code goes here
  return cleanParam;
}

但这会非常冗长和重复(记住,我有数百个这样的函数)。

我的问题是:通过 cleanUp 函数透明地传递所有函数参数的最佳方法是什么,可以是继承,也可以是更合适的方法。我知道我可以使用 arguments 变量来访问所有函数的参数,但我希望清理发生在函数本身的外部,进入一些其他函数我的功能可以“继承”自。

注意:在所有函数中,为了便于阅读,参数必须保留其原始名称。

最佳答案

我想我的问题措辞不当,但我仍然不确定如何改进它。

无论如何,这是我从同事那里得到的答案。以一种危险的方式,如果有人可以改写我最初的问题以匹配我正在寻找的答案,我会很高兴,因为我很确定由此产生的问答具有一定的值(value)。

// Parameter cleanup function
function cleanUp(param) {
  // Cleanup code goes here
  return cleanParam;
}

// Implementation of one of the hundreds of functions in the library
function _myFunction(param1, param2, ..., paramN) {
  // Function's implementation goes here
}

// Proxy of one of these functions with clean parameters
function myFunction = makeProxy(_myFunction);

// Utility function to create a proxies for the library functions
function makeProxy(fn) {
  function proxy() {
    var cleanParams = [];
    for (var i = 0; i < arguments.length; i++) {
      cleanParams.push(cleanUp(arguments[i]));
    }
    return fn.apply(this, cleanParams);
  }
  return proxy;
}

谢谢帕斯卡!

关于javascript - 通过另一个函数透明地传递一个函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14585077/

相关文章:

casting - C++17: "operator with precedence below cast"在 "fold"概念中是什么意思?

将 void* 转换为其他类型

javascript - ajax post to jboss eap 7 without encodeURIComponent occurred messy code

javascript - 为什么Object.prototype的__proto__是另一个Object.prototype?

javascript - 在不覆盖当前函数体的情况下扩展 javascript 函数

java - super.a = b 而不是 super(b)

java - 转换是否会在运行时更改声明/引用类型?

javascript - 无法解析 JSON 数组

javascript - 如何防止 Angular JS 中的确认对话框出现默认值

javascript - 为什么数组中的字符串索引不会增加 'length' ?