2

I'm building a fairly large JavaScript library made of hundreds of functions. Each function has a certain number of parameters, sometime not known at design time. I need to pipe every function parameter through some kind of parameter cleanUp() function. I could do something like that:

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;
}

But that would be quite verbose and repetitive (remember, I have hundreds of these functions).

My question is: what would be the best way to transparently pipe all the function's parameters through the cleanUp function, either with inheritance, or anything more appropriate. I know that I can use the arguments variable to access all the functions' parameters, but I would like the cleanup to happen outside of the functions themselves, into some other function that my functions could "inherit" from.

Note: within all the functions, parameters must keep their original names for readability purposes.

4

3 に答える 3

1

私は自分の質問を適切に表現していなかったと思いますが、それを改善する方法はまだわかりません.

とにかく、これは私が職場の同僚から得た答えです。ジェパディのような方法で、私が探していた答えに一致するように、誰かが私の最初の質問を言い換えてくれるとうれしいです.

// 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;
}

ありがとうパスカル!

于 2013-01-29T20:34:07.193 に答える
0

関数で 'arguments' 変数を使用します。それは...ええと...すべての引数のリストです:-)

function test (a,b) {
   console.log(arguments);
}
test('test','test');
于 2013-01-29T14:25:16.213 に答える
0

// 内部引数オブジェクトを渡す

function myFunction(param1, param2, ..., paramN) {
  var paramters = cleanUp(arguments);
}
于 2013-01-29T14:25:40.073 に答える