Closures are used quite frequently in Javascript for tasks such as adding event listeners or setting timeouts on function calls. Closures are where a function is passed as a parameter to a function call from another function, and variables from the calling function must be used inside the parameter function. Dealing with scope in closures can be difficult, and I’ve spent a lot of time figuring issues with them out.
An early issue I ran into with scope, and a common one, is the loss of scope of the “this” keyword in the closed function. For example, you might want to do a setInterval that references the object that created it. To do so, you can simply create a variable pointing to “this” and then use that in the closed function, like:
class.prototype.thefunction = function(){
var fncThis = this;
setInterval(function(){ fncThis.doSomething(); }, 1000);
}
This is also a common problem with event listeners, where “this” might be hoped to point to the element the listener is related to, but doesn’t.
Recently, I ran into a closure problem while revamping the menu script we use at Cogneato for suckerfish menus from the old MM functions to something more capable.
Continue reading post "Javascript: Closures, Scope, and Arrays"