Reputation: 3381
I've written an if statement in .js file outside any function which means its in Global Scope, right?
Here is the code Snippet:-
if ((window != window.parent) && (document.referrer.indexOf("facebook") != -1)) {
window.fbAsyncInit = function() {
FB.init({
appId : '...',
status : true,
xfbml : true
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
}
Is it better to write this statement in the following manner:-
(function() {
if ...
})();
What is the benefit of doing so? and what are these type of functions called?
Upvotes: 1
Views: 55
Reputation: 34576
They are called immediately-executed functions (IEF). You will often hear them called self-executing functions, but this is something of a misnomer; they do not self-execute, they are executed by you, but immediately.
The benefit is you protect the global scope from pollution. This can prevent conflicts between libraries and plugins, say, and is also useful for things like strict mode, part of the philosophy of which is that everything is contained in a closure of some sort.
I wouldn't have lots of IEFs; consider having one for your whole script. Alternatively you can achieve global closure by using something like the object pattern.
Upvotes: 2