jquery - JavaScript Statements in Global Scope -
i've written if statement in .js file outside function means in global scope, right?
here 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 better write statement in following manner:-
(function() { if ... })();
what benefit of doing so? , these type of functions called?
they called immediately-executed functions (ief). hear them called self-executing functions, of misnomer; not self-execute, executed you, immediately.
the benefit protect global scope pollution. can prevent conflicts between libraries , plugins, say, , useful things strict mode, part of philosophy of contained in closure of sort.
i wouldn't have lots of iefs; consider having 1 whole script. alternatively can achieve global closure using object pattern.
Comments
Post a Comment