Thursday 14 June 2018

JavaScript scope and closure



I'm trying to wrap my head around closures (there's a joke in there somewhere) and I ran across this:




(function () { /* do cool stuff */ })();


How does this work? What's the purpose of putting the function in parens? Why the empty parens afterwards?


Answer



The point of this is that any variables declared in the cool stuff will not be created in global namespace. Any function in javascript will create such a scope. Suppose you have some javascript you want to run. If you do this:



var b = 1; 
// stuff using b



And some other code uses b, it will get your left over value. (Or, even worse, if some other code sets b before your code runs, then tries to get its old value later, you'd have changed it in the meantime.)



On the other hand, if you have this code, which declares and then calls the a function:



function a() { 
var b = 1;
}


a();


And some other code later on uses b, it will not see your values, since b is local to the function. The problem with this, of course, is that you're still making a global name - "a", in this case. So, we want a function with no name - this is why you get the code you described. It declares a function with no name, and then calls it.



Unfortunately, you can't just say:



function() { ... }()



because this will be parsed as a function declaration statement, and then a syntax error. By wrapping the function declaration in parenthesis, you get a function expression, which can then be called. You call it like any other function expression (like a, above), using the second set of parens. For example, if the function took arguments, you'd pass them there:



(function(a) { ... })(1)

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