title: TypeError: this is undefined
body: <pre><code>function foo(obj, method, ...args) {
    if (!(method in obj)) return null;
    try {
      alert(!!obj); //shows true
      return obj[method].apply(obj, args);
    }
    catch (e) {
      alert(e);
    }
  }
  </code></pre>
  
  <p>When I call <code>foo</code> with a defined object, a valid method of it and some args, it shows:
  <code>TypeError: this is undefined.</code></p>
  
  <p>What does this mean? </p>
  
  <p>I thought <code>this</code> would be important here because I'm using <code>apply</code> whose 1st param will be used as <code>this</code> inside the method invoked. But here <code>obj</code> is valid and it doesn't even invoke the required method. An error is caught even before.</p>
  
  <p>(<code>...args</code> means any extra arguments passed to <code>foo</code> after <code>obj</code> and <code>method</code> will be pushed into an array <code>args</code> which can be used by <code>foo</code>)</p>
  
  <p><strong>EDIT:</strong> <code>...args</code> is valid. It's ES6.</p>
  
  <p><strong>EDIT</strong>: My code seems perfectly fine. I'm trying to check and see if the called function has something wrong. Sorry if that is the case.</p>
  
  <p><strong>EDIT</strong>: I'm sorry, the problem turned out to be with the method that was being invoked. I had said otherwise, but I was confused. </p>
  
  <p>There was another callback in it.</p>
  
  <pre><code>array.forEach(function (a) { // do something with 'this'});
  </code></pre>
  
  <p><code>this</code> was obviously being undefined since it didn't refer to the object.</p>