title: Dynamically add argument to function in javascript
body: <p>I'm testing my app, I have a dependency injection system that works like this (I paste here a very simplified version)</p>
  
  <pre><code>test.start = function(callback) {
    // do stuff;
    load(callback);
  }
  function load(callback) {
    var args = ...// read callback's arguments
    // args = ['moduleA', 'moduleB'];
    var injectedArgs = args.map(function(a) {
      return require('./lib/' + a);
    });
    // call function with deps injected
    callback.apply(null, injectedArgs);
  }
  
  // test.js
  test.start(function(moduleA, moduleB) {
    moduleA.functionA();
    moduleB.functionB();
  });
  </code></pre>
  
  <p>What I need to do is an async job before calling the callback and start the test, in this particular case, that would be</p>
  
  <pre><code>test.start = function(callback) {
    // do stuff;
    load(function(moduleA, moduleB, moduleC) {
      moduleC.resetData(function() {
        return callback(moduleA, moduleB);
      })
    });
  }
  </code></pre>
  
  <p>I need to make this dynamic, for all the test that have different modules as their callback arguments.
  Requirements are</p>
  
  <ul>
  <li>I don't want to change test definitions </li>
  <li>I must call <code>load</code> only once per test</li>
  </ul>
  
  <p>So basically I need to create the middle function that add <code>moduleC</code> argument, run the <code>resetData</code> function and call the original callback.</p>
  
  <p>I can build the dynamically extended argument list using 
  <code>var fn = new Function(newArgumentList, /*function body*/)</code> but I can't attach the correct function body (using a string) because I lose the original callback context.</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>The DI library is <a href="https://www.npmjs.com/package/modularity" rel="nofollow">modularity</a> and it reads the callback definition to grab dependency. So basically, given the callback <code>function(foo, bar) { ... }</code> I need to create a new <code>function(foo, bar, db) { db.resetData(function() { return callback(foo, bar) } )}</code></p>