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,201
  • 2
  • 23
  • 28
Kevin
  • 23,174
  • 26
  • 81
  • 111

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,195
  • 2
  • 22
  • 52
0

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

Evan Hahn
  • 12,147
  • 9
  • 41
  • 59
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
  • 23,282
  • 5
  • 60
  • 71