title: JavaScript prototypes: replace a function
body: <p>I want to decorate a function of a JavaScript "class" (prototype):</p>
  
  <pre><code>SomeClass = function() { this.someVar = 5; };
  
  SomeClass.prototype = {
      foo: function(arg) { /* do something with this.someVar */ }
  }
  </code></pre>
  
  <p>However, I cannot change the source of <code>SomeClass</code> nor am I able to influence the instance creation of <code>SomeClass</code> instances.</p>
  
  <p>Therefore I thought about doing the following:</p>
  
  <pre><code>var oldFoo = SomeClass.prototype.foo;
  SomeClass.prototype.foo = function(arg) {
      console.log("Yey, decorating!");
      oldFoo(arg);
  };
  </code></pre>
  
  <p>This seems to work fine, however, due to function scoping <code>oldFoo</code> cannot access <code>someVar</code> anymore (the <code>this</code> object is now <code>window</code>). How to overcome this issue?</p>