Possible Duplicate:
Is it possible to gain access to the closure of a function?
Say I have the following implementation of the revealing module pattern:
var myModule = (function() {
var myVar,
_self = this;
function setMyVar( myVar ) {
_self.myVar = myVar;
}
return {
setMyVar: setMyVar
}
})()
myModule.setMyVar('happy');
What I want to do is set the module level myVar to be ‘happy’. This doesn’t work because ‘this’ is equal to window in the anonymous parent function. One easy work around would be to avoid child-parent name collisions, but putting that aside, is there a way I could have access to a reference to the anonymous function scope from inside a nested child function?
Please don’t consider that to be a workaround, but rather a best practice. Variable shadowing doesn’t often add benefit, but can add confusion to code and bugs when you forget which variable you’re working with.
The only variable scope (or variable object, or binding object… whatever) that is available as an object that can be directly manipulated in code is the “global” scope. No nested scopes allow this sort of direct access, so no, there’s no other option other than to avoid shadowed variables.
This should generally not be an issue. A function variable or parameter can only access (and therefore shadow) variables in its original scope, so passing a function into a different scope will not cause any sort of conflict with the variables in that scope.
If needed, code validators like http://jshint.com are able to catch shadowed variables for you.