Friday 5 January 2018

javascript - What are the benefits of a closure, and when are they typically used?

itemprop="text">

I'm a web developer, but lots of folks
are looking for slightly more advanced skills and understanding closures seems to be at
the forefront of this.



I get the whole
"execution context creating a reference to a variable that doesnt ever get destroyed"
thing, but really, is this some sort of private or static variable implementation in
JavaScript?



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



They can
be good for lots of things, for example, visibility (like private members in traditional
OO).



var count = function(num)
{

return function(add) {
add = add || 1;
num
+= add;
return num;

}


}


href="http://jsbin.com/onuya3/edit" rel="nofollow noreferrer">See
it.



My
count() can be seeded with a number. When I assign a variable
to the return, I can call it with an optional number to add to the internal
num (an argument originally, but still part of the scope of the
returned function).



href="http://www.javascriptkit.com/javatutors/closures.shtml" rel="nofollow
noreferrer">This is a pretty good
overview.




See also on




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...