Simple, why do some js files (such as Ember or JQuery.js) begin with (function() {...})();
?
In JavaScript, a function allows you to define a block of code, give it a name and then execute it as many times as you want. A JavaScript function can be defined using function keyword.
If I'm understanding your question I think you're asking if it matters where in a file a function/method is defined, and the answer is no, you can define them anywhere in a single source file. The JavaScript parser will read in all symbols before trying to run the code.
To declare a function, you use the function keyword, followed by the function name, a list of parameters, and the function body as follows: function functionName(parameters) { // function body // ... } The function name must be a valid JavaScript identifier.
Code of the form (function() { /* code here */ })()
is known as an "Immediately Invoked Function Expression". It is frequently used to set up a closure, so you can define variables without polluting the global scope. You find it in Ember, jQuery, and pretty much every other "plug-in" for this reason. Polluting the global scope is generally a bad idea, but with plug-ins that must work on all sites it is especially important to make sure it doesn't accidentally overwrite a variable the site's creator is using.
Of course, there are other uses. For instance, it can be used to "anchor" an iterating variable, like so:
for( i=0; i<links.length; i++) {
(function(i) {
links[i].onclick = function() {alert(i);};
})(i);
}
// without the IIFE, all links would alert the value of links.length instead.
There are also some cases I occasionally use IIFEs that most people would probably lynch me for, such as a "just-in-time" computation:
if( (function() {
var party=document.getElementById('party').children, l=party.length, i, r=0;
for( i=0; i<l; i++) if( party[i].children.length > 0) r++;
return r;
})() == 6) {
// your Party is full
}
The above would be much better if it were calculated before jumping into the if
statement, so... do not do as I do on this one!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With