0
   var x = 5,
    o = {
        x: 10,
        doIt: function doIt(){
            var x = 20;
            setTimeout(function(){
                alert(this.x);
            }, 10);
        }
    };
o.doIt();

Why is this referring to window object rather than o. I am inside the object o context, so it should print me 10 right?

Saju
  • 3,117
  • 2
  • 22
  • 28
Kevin
  • 22,496
  • 25
  • 78
  • 110

3 Answers3

4

The anonymous function is executed after 10ms, and the execution context is not in o at that time.

Check out the answers to How do JavaScript closures work?

Community
  • 1
  • 1
Osiris
  • 4,127
  • 2
  • 18
  • 50
0

To make this alert 20, change this.x to simply x.

Evan Hahn
  • 11,058
  • 7
  • 35
  • 47
0
var x = 5,
    o = {
        x: 10,
        doIt: function doIt(){
            var x = 20;
            setTimeout(function(){
                alert(this.x);
            }, 10);
        }
    };
o.doIt();

All functions passed into setTimeout() are executed in the global scope. The value is 5 because this.x is the same as window.x

Thalaivar
  • 22,304
  • 5
  • 59
  • 68