Posts Tagged javascript
JavaScript scoping
Posted by Carlos Daniel in Coding on July 30, 2011
When working with JavaScript is quite common to use closures, but also quite easy to forget you are using them and have problems with scoping, lets take the following example of a class A, where we have a function that is called from setInterval:
function A(){
this.x = 32;
}
A.prototype.showAlarm = function(){
alert(this.x);
}
A.prototype.setAlarm = function(interval){
setInterval(this.showAlarm, interval);
}
alarm = new A(); alarm.setAlarm(5000);
This should show a message in 5 seconds with the number 32 (defined on x), however if you run this it gives [undefined], why is that?, when setInterval calls the given function some variables changes and you may not be aware of that, this no longer points to A instance, it points to window instance (which has the setInterval function), however, closures conserving the environment can be used to call the real function:
A.prototype.setAlarm = function(interval){
var that = this;
setInterval(function (){ that.showAlarm(); }, interval);
}
If you look closely now we are passing a closure to setInterval, thus closure then calls showAlarm, however note that we replaced ‘this’ for ‘that’, the reason being that inside the closure this will be the window but any other variables will be preserved from the environment.