javascript - Why this is referring the outside variable? -
this question has answer here:
this should refer object in following code why it's behaving differently?
var x = 4, obj = { x: 3, bar: function() { var x = 2; settimeout(function() { var x = 1; alert(this.x); }, 1000); } }; obj.bar();
why alert 4
instead of 3
?
inside settimeout
callback this
refers window object, it's retrieving variable defined in global context.
you can make working binding context using function#bind
method .
var x = 4, obj = { x: 3, bar: function() { var x = 2; settimeout(function() { var x = 1; alert(this.x); }.bind(this), 1000); } }; obj.bar();
or use local variable cache reference this
, use inside callback function.
var x = 4, obj = { x: 3, bar: function() { var x = 2, = this; settimeout(function() { var x = 1; alert(that.x); }, 1000); } }; obj.bar();
also refer mdn documentation : the "this" problem
Comments
Post a Comment