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();
Your question may be due to the misunderstanding of your issue.
y
is not defined in a functional scope off()
, and you never assign a value to it. They
ing()
is scoped to that function.In your example:
If
g()
used the globaly
, theny
inf()
will be defined at run-time. Drop thevar
keyword ing()
to create a globaly
at compilation-time.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.