Search code examples
javascriptscopeclosureschainlexical-scope

switch off lexical scoping in javascript


Is it possible to change the lexical scoping of javascript so that functions use the variable scope that is in effect when they are evoked not when they were defined? In a nutshell can I change the scope chain associated with a function?

An example for this: I would like to be able to execute something like this without getting the error message, that y is not defined:

function f(){y+2};
function g(){
 var y=2;
 f();
 return y;
}
g();

Solution

  • Your question may be due to the misunderstanding of your issue. y is not defined in a functional scope of f(), and you never assign a value to it. The y in g() is scoped to that function.

    In your example:

    function f(){ y+2 };
    function g(){
      var y=2;
      f();
      return y;
    }
    g();
    

    If g() used the global y, then y in f() will be defined at run-time. Drop the var keyword in g() to create a global y at compilation-time.

    function f(){ y+2 };
    function g(){
      y=2;
      f();
      return y;
    }
    g();
    

    NOTE: Creating globally scoped variable like this is possible, but NOT recommended. Since your example is contrived and only being used to understand scope, it won't hurt anything.