title: Overwrite and restore a function
body: <p>I need to mock call a function in JavaScript. For this, I'm "saving" the function in a temporary variable, update the target with a new function block, calling the target and then restoring the old function:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var myObject = {
    myIntProp: 1,
    myFunc: function(value) {
      alert(value + 1);
    }
  };
  myObject.myFunc(2);
  
  var tmp = myObject.myFunc;
  myObject.myFunc = function(value) {
    alert(value - 1);
  };
  myObject.myFunc(2);
  
  myObject.myFunc = tmp;
  myObject.myFunc(2);</code></pre>
  </div>
  </div>
  </p>
  
  <p>This works as expected: the function gets overwritten and then successfully restored. My thought was to move this code into a helper function and easily use it when needed:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function FunctionSwapper(target, newFunction) {
    var old = target;
    target = newFunction;
    this.Restore = function() {
      target = old;
    }
  };
  
  var myObject = {
    myIntProp: 1,
    myFunc: function(value) {
      alert(value + 1);
    }
  };
  myObject.myFunc(2);
  
  var swapp = new FunctionSwapper(myObject.myFunc, function(value) {
    alert(value - 1);
  });
  myObject.myFunc(2);
  
  swapp.Restore();
  myObject.myFunc(2);</code></pre>
  </div>
  </div>
  </p>
  
  <p>This code however, does not save the current state nor is it replacing the targeted function. What am I missing here? Isn't a function always passed as reference? What are the main differences between the two code snippets?</p>
  
  <p>(<a href="http://jsfiddle.net/oc1xhc9j/" rel="nofollow">JSFiddle</a> available, but prepare for 8 <code>alert</code>s...)</p>
  
  <p>Edit: a fellow user has pointed out that the second method does not really differ from the first one and that it's probably not worth the trouble of creating the additional class; while I do understand and agree with their arguments, I see two advantages in the second method (both apply to my <em>particular</em>, real-world case):</p>
  
  <ol>
  <li>it's easier/faster to write <code>swapp.Restore();</code> than <code>myNameSpace.level2.level3.level4.level5 = swap;</code> when working with objects which have several levels of child elements and,</li>
  <li>it abstracts the operation, providing a consistent use among the development team (additionally, logging or type proofing could be done inside the class). </li>
  </ol>