Question

I have a scope problem. I have the following code that implements the revealing module pattern:

myModule = function(){

  var foo = "ohai";

  function sayOhai(foo){
      alert(foo);
  };

  return{
    sayOhai : sayOhai
  };

}();

myModule.sayOhai("configData");

Which results in a Dialogue "configData".

However, I want the function sayOhai to say "ohai" using the defined var. Assumed i do not want to change the parameter name of sayOhai, how can i access foo's value within sayOhai? I tried alert (this.foo), but that is undefined.

Again, this is a theoretical question, so changing sayOhai(foo) is not a solution i'm looking for. The var's name and the method's parameter should stay the same. So, from the scope of sayOhai, what's the full qualified name of var foo?

Thanks in advance

Was it helpful?

Solution

I want the function sayOhai to say "ohai" using the defined var. Assumed i do not want to change the parameter name of sayOhai, how can i access foo's value within sayOhai?

You simply can't. The var foo is shadowed by the inner function parameter with the same name.

OTHER TIPS

It can't be done as you have requested.

When you define var foo = "ohai"; in the function and then return a closure, foo is now private.

In the function sayOhai, you have an argument with the same name as a variable declared above it in the lexical scope.

Therefore, the function's argument named foo always wins.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top