title: JavaScript closure and the this object
body: <p>I thought I had a reasonable understanding of the <code>this</code> object in JavaScript. When dealing with objects, callbacks, and both events and handlers, I haven't had a problem with it since time immemorial. Now, however, all has changed. </p>
  
  <p>I've fallen head over heels in love with JavaScript. Pure JS, that is, not jQuery, prototype.js, dojo... So naturally, I've taken to using closures. In some cases, though, <code>this</code> is catching me off guard here. Take this snippet for one:</p>
  
  <pre><code>function anyFunc(par)
  {
      //console.log(par);
      console.log(this);
  }
  
  function makeClosure(func)
  {
      return function(par)
      {
          return func(par);
      }
  }
  var close = makeClosure(anyFunc);
  close('Foo');
  
  var objWithClosure = {cls:makeClosure(anyFunc),prop:'foobar'};
  objWithClosure.cls(objWithClosure.prop);
  
  var scndObj = {prop:'Foobar2'};
  scndObj.cls = makeClosure;
  scndObj.cls = scndObj.cls(anyFunc);
  scndObj.cls(scndObj.prop);
  </code></pre>
  
  <p>In all three cases, <code>this</code> logs as the window object. It's an easy fix, of course:</p>
  
  <pre><code>function makeClosure(func)
  {
      return function(par)
      {
          return func.call(this,par);
      }
  }
  </code></pre>
  
  <p><em>This fix works, I put it here to avoid people answering this, without explaining what I need to know: why is this behaving the way it does here?</em></p>
  
  <p>ensures the caller is effectively the object that the closure belongs to. What I fail to understand is this:
  Sure enough, <code>this</code> points to the window object in the first case, but in other cases, it shouldn't. I tried logging <code>this</code> in the makeClosure function just before returning, and it did log the object itself, not the <code>window</code> object. But when the actual closure is used, <code>this</code> is back to pointing to the window object. Why? </p>
  
  <p>The only thing I can think of is that, by passing the <code>anyFunc</code> function as an argument, I'm actually passing <code>window.anyFunc</code>. So I tried this quick fix:</p>
  
  <pre><code>function makeClosure(func)
  {
      var theFunc = func;
      return function(par)
      {
          theFunc(par);
      }
  }
  </code></pre>
  
  <p>With the expected results, <code>this</code> now points to the objects, but again: Why? I have a few idea's (<code>theFunc</code> is a reference to the function in the local scope [<code>this &gt; private: theFunc</code>]?), but I'm sure there are people here with a lot more know-how when it comes to JS, so I was hoping to get some more explanation or links to articles worth reading from them... </p>
  
  <p>Thanks</p>
  
  <p><strong>Update</strong></p>
  
  <p><a href="http://jsfiddle.net/3chdp/" rel="nofollow">Here's a fiddle</a>, may be I left something out, but here this logs all sorts of things ;)</p>
  
  <p><strong>Edit/Update 2</strong></p>
  
  <p><a href="http://jsfiddle.net/7Skbc/1/" rel="nofollow">The case that confuses me</a> is here.</p>
  
  <p><strong>Final Edit</strong></p>
  
  <p>Ok, This is getting a rather messy post. So to clarify: What I was expecting was a behaviour similar to this:</p>
  
  <pre><code>function makeClosure()
  {
      function fromThisFunc()
      {
          console.log(this);
      }
      return fromThisFunc;
  }
  
  var windowContext = makeClosure();
  windowContext();
  var objectContext = {cls:makeClosure()};
  objectContext.cls();
  </code></pre>
  
  <p>What caught me, was that the function <code>anyFunc</code> wasn't declared within the correct scope, and therefore, <code>this</code> pointed to the window object. I found this out by reading an <a href="http://jibbering.com/faq/notes/closures/#clEncap" rel="nofollow">ancient scroll</a> I found somewhere on the web.</p>
  
  <blockquote>
    <p>But something a little more complicated has happened because the function object now referred to by globalVar was created with a [[scope]] property referring to a scope chain containing the Activation/Variable object belonging to the execution context in which it was created (and the global object). Now the Activation/Variable object cannot be garbage collected either as the execution of the function object referred to by globalVar will need to add the whole scope chain from its [[scope]] property to the scope of the execution context created for each call to it.</p>
  </blockquote>
  
  <p>So what I needed to do, was simplify rather then complicate things:</p>
  
  <pre><code>function fromThisFunc()
  {
      console.log(this);
  }
  
  function makeClosure(funcRef)
  {
      //some code here
      return funcRef;
  }
  </code></pre>
  
  <p>That should work, right?</p>
  
  <p>PS: I'll except Alnitak's answer, but special thanks goes to Felix Kling for all the patience and info. </p>