title: How do I wrap a function in Javascript?
body: <p>I'm writing a global error handling "module" for one of my applications.</p>
  
  <p>One of the features I want to have is to be able to easily wrap a function with a <code>try{} catch{}</code> block, so that all calls to that function will automatically have the error handling code that'll call my global logging method. (To avoid polluting the code everywhere with try/catch blocks).</p>
  
  <p>This is, however,  slightly beyond my understanding of the low-level functioning of JavaScript, the <code>.call</code> and <code>.apply</code> methods, and the <code>this</code> keyword.</p>
  
  <p>I wrote this code, based on Prototype's <code>Function.wrap</code> method:</p>
  
  <pre><code>Object.extend(Function.prototype, {
    TryCatchWrap: function() {
      var __method = this;
      return function() {
              try { __method.apply(this, arguments) } catch(ex) { ErrorHandler.Exception(ex); }
      }
    }
  });
  </code></pre>
  
  <p>Which is used like this:</p>
  
  <pre><code>function DoSomething(a, b, c, d) {
      document.write(a + b + c)
      alert(1/e);
  }
  
  var fn2 = DoSomething.TryCatchWrap();
  fn2(1, 2, 3, 4);
  </code></pre>
  
  <p>That code works perfectly. It prints out 6, and then calls my global error handler.</p>
  
  <p>My question is: will this break something when the function I'm wrapping is within an object, and it uses the "this" operator? I'm slightly worried since I'm calling .apply, passing something there, I'm afraid this may break something.</p>