Skip to content Skip to sidebar Skip to footer

How To Access Variable In The Anonymous Closure Parent Scope From A Nested Function If Both Contain Variables Of The Same Name?

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

Solution 1:

"One easy work around would be to avoid child-parent name collisions"

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.

Solution 2:

No. If it is masked, it is masked and you can't get access to it.

Post a Comment for "How To Access Variable In The Anonymous Closure Parent Scope From A Nested Function If Both Contain Variables Of The Same Name?"