Maintaining Scope with setTimeout();
Mar 11, 2008 in and JavaScript
Needing to execute an instance method after a certain time interval with passed parameters, using something like the code below does not suffice.
setTimeout("this.instanceMethod("+ arg1 +","+ arg2 +", ...);", 500);
The code above must be passed as a string to prevent execution when the timeout is set, and worse, the window that the timeout code executes within does not understand what this is referring to; instanceMethod() cannot be located.
Function Closures
One property of JavaScript as a dynamic language is the flexibility to add properties to methods at runtime. A function closure is a special function definition property making local variables of the definer's scope accessible within the definee's scope. Using a function closure in combination with this scope knowledge, the following modification to the code to be executed by setTimeout is derived.
// ... this code is executing within an object instance
callingMethod: function(){
var _self = this;
setTimeout(function(){
_self.instanceMethod(arg1, arg2, ...);
}, 500);
}
_self contains a reference to the defining object, allowing instanceMethod() to be referenced properly once the timeout expires.
D4Ly..com ©2006