Saturday 30 December 2017

deeper understanding of closure in Javascript

itemprop="text">


I was reading the comments
on an answer and saw href="https://stackoverflow.com/questions/15667093/how-to-understand-closure-in-javascript/15667314#comment22237952_15667362">this
comment:





[the closure] doesn't persist the state of foo so much as creates a special
scope containing (1) the returned function and (2) all the external variables referenced
at the time of the return. This special scope is called a closure.




OK, so far so
good. Now here is the interesting part that I didn't know
about:






Case in point... if you had another var defined in foo that was
not referenced in the return function, it would not exist
in the closure
scope.




I guess
that makes sense, but what implications does this have other than memory use /
perfomance
?



Question -- If all
variables in scope were included in the closure, what would that allow me to do that I
cannot do with the current model?


class="post-text" itemprop="text">
class="normal">Answer



I think
you're taking that comment too literally. The comment is just saying that you can't
access it outside the function scope (it's not publicly accessible), not that its not
available at all within the function. The returned function will have access to all of
the outer functions scope no matter what. You just can't access that scope outside the
outer function if the inner function doesn't provide a way of accessing
it.



For instance, this expression evaluates to
4:




function
testClosure(){
var x = 2;
return function(y){

alert(eval(y));
}

}

var closure =
testClosure();


closure("x+2");
//4


href="http://jsfiddle.net/dmRcH/" rel="nofollow
noreferrer">http://jsfiddle.net/dmRcH/



So
x is available despite not being directly
referenced



Further
research




It appears that chrome and
firefox at least do attempt to optimize this in the sense that if you're not providing
ANY way to reference the x variable, it doesn't show up as
being available in the debugger. Running this with a breakpoint inside a closure shows
x as unavailable on Chrome 26 and Firefox 18.



rel="nofollow
noreferrer">http://jsfiddle.net/FgekX/1/



But
thats just a memory management detail, not a relevant property of the language. If there
is any possible way that you could reference the variable, it is passed, and my
suspicion is that other browsers may not optimize this in the same way. Its always
better to code to the spec than to an implementation. In this case though the rule
really is: "if there's any possible way for you to access it, it will be
available"
. And also, don't use eval because it really will
keep your code from optimizing anything
.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...