The whole idea of "trick" in programming is wrong.
Short answer is: you cannot access a local variable, and it makes no sense because such variables are placed on stack; and the stack frame is removed after the return from a function.
But let's go deeper. Strictly speaking, this is not always exactly so, because you can make some local variable a part of the
closure. Please see:
https://en.wikipedia.org/wiki/Closure_%28computer_programming%29[
^].
Let's consider the following JavaScript:
function getAccessToLocalVariable() {
var localVariable = 0;
return function() {
localVariable++;
return localVariable;
}
}
var incrementor = getAccessToLocalVariable();
alert(incrementor());
alert(incrementor());
If you run the "test it" fragment, you will get the value of
localVariable
incremented on each call. Of course, you could return an object which gives direct access to the variable, through two functions returned in this object: one for "getter", another one for "setter":
function getAccessToLocalVariable() {
var localVariable = 1;
var getter = function() {
return localVariable;
}
var setter = function(value) {
localVariable = value;
}
return {"getter": getter, "setter": setter};
}
var accessor = getAccessToLocalVariable();
alert(accessor.getter());
accessor.setter(10);
alert(accessor.getter());
It's much easier to implement than to explain how it works. I hope the article I referenced above can help you to understand it. First of all, throw out the common misconception that JavaScript is a pure interpreter which process statements one by one. No, it does forward
lexical analysis and some pre-processing first. So, when the JavaScript engine detects that some function accesses some objects from the outer context, such as
getter
accessing
localVariable
, and the object is accessed through some local variable of the outer context, this local variable changes the way it is stored: it joins the closure, which should be understood as a set of objects "with extended lifetime". Roughly speaking, the objects from this set behave exactly as the object of the global context, but the variables used to access them behave like local variables.
The techniques based on closures can be very useful, because they can help you to hide some context intended to serve as
implementation detail, with limited and controlled access from outside context. Of course, the second example makes little practical sense; but such technique (called
property feature in object-oriented languages) is introduce to implement some
side effect in addition to usual read/assign semantics. Of course, there are many other applications of closures.
—SA