Search code examples
javascriptfunctionscopeself-executing-function

Accessing Shadowed Variable in Self Executing Function


In the following example, is there any way to get a reference to the someValue variable declared outside someFunction from within someFunction or is it completely obscured by the function's parameter of the same name. I appreciate that I could attach it to window and access it from within the function using this, but is there a way of accessing it in this situation?

[Edit] To clarify. I understand that the parameter is shadowing the variable. Obviously changing the name of the parameter would remove this issue. My question is whether there is any way to access the variable given this situation.

(function($){

   var someValue = 41;

   function someFunction(someValue) {

      console.log(someValue); //= 22

   }

   someFunction(22);


}(jQuery));

Solution

  • You seem to be deliberately shadowing the variable, and then trying to get its value. Just give it a different name or rename your parameter.

       var someValue = 41;
       function someFunction(myParameter) {
          console.log(someValue); // someValue == 41
       }
       someFunction(22); // logs 41