Reputation: 14967
My query is used in cases that "(function() {...})();" Given that I am not a plugin. For example "http://piecesofrakesh.blogspot.com/2009/03/downloading-javascript-files-in.html"
(function() {
var s = [
"/javascripts/script1.js",
"/javascripts/script2.js"
];
var sc = "script", tp = "text/javascript", sa = "setAttribute", doc = document, ua = window.navigator.userAgent;
for(var i=0, l=s.length; i<l; ++i) {
if(ua.indexOf("MSIE")!==-1 || ua.indexOf("WebKit")!==-1) {
doc.writeln("<" + sc + " type=\"" + tp + "\" src=\"" + s[i] +
"\" defer></" + sc + ">");
} else {
var t=doc.createElement(sc);
t[sa]("src", s[i]);
t[sa]("type", tp);
doc.getElementsByTagName("head")[0].appendChild(t);
}
}
})();
Or
var s = [
"/javascripts/script1.js",
"/javascripts/script2.js"
];
...
Thank you.
Upvotes: 8
Views: 487
Reputation: 125538
(function() {...})();
is a self-invoking anonymous function i.e. a function with no name that is executed straight away. Since JavaScript has function scope, using self-invoking anonymous functions limits the scope of variables inside the function to the function itself, thereby avoiding any conflicts that might occur otherwise.
In jQuery, a self-invoking anonymous function is used quite often by plugin authers to reference the jQuery object with the $
symbol inside of the function. For example
(function($) {
/* plugin code here */
})(jQuery);
Upvotes: 3
Reputation: 8953
Idiom (function() {...})();
limits scope of your variables. So in first case s
(and sc
, tp
etc) won't be accessible anywhere outside function body. In second case you will be able to access it. So (function() {...})();
keeps you from namespace pollution. Whether you need that is another question. You may like to google something like "scope javascript". There's a nice article.
Upvotes: 2
Reputation: 109503
Maybe these questions will help you out:
Upvotes: 6
Reputation: 10276
This is done to avoid naming conflicts.
When you declare a function, that function has its own namespace for variables. By wrapping the code in a function that is immediately invoked, you avoid overwriting global variables with your own values.
In this case s
and sc
are assigned a value. If you did that at the global scope and other scripts were already using variables with those names for a different purpose, that would cause those other scripts to fail. By introducing the new scope, the identifiers s
and sc
now refer to different (locally-bound) variables than the variables named s
and sc
that exist at the global scope.
Upvotes: 24