what does 'this' refer to in Javascript functions
<p>I understand the general idea behind the <code>this</code> keyword but I'm having trouble figuring out what it actually refers to in practice. For example, in both these example exercises, I guessed the wrong number. </p>

<p>for question1, I said that the alert would be '5', because it is referring to the this.x outside the anonymous function in the function. </p>

<p>In question2, I thought the alert would be 5 because this line</p>

<pre><code>var alertX = o.alertX;
</code></pre>

<p>would bind the value 5 for property x inside the variable o to the new variable 'alertX' which becomes the function call in the next line:  alertX();</p>

<p>Can you explain why I'm wrong? </p>

<pre><code>var question1 = function() {
    this.x = 5;
     (function() {
        var x = 3;
        this.x = x;
    })();
    alert(this.x);
};
var answer1 = 3; 


var question2 = function() {
    this.x = 9;
    var o = {
        'x':5,
        'alertX':function() { alert(this.x); }
    };
    var alertX = o.alertX;
    alertX();
}
var answer2 = 9; 
</code></pre>
