Monday 26 December 2016

javascript - Why is this function wrapped in parentheses, followed by parentheses?




I see this all the time in javascript sources but i've never really found out the real reason this construct is used. Why is this needed?




(function() {

//stuff

})();


Why is this written like this? Why not just use stuff by itself and not in a function?




EDIT: i know this is defining an anonymous function and then calling it, but why?


Answer



This defines a function closure



This is used to create a function closure with private functionality and variables that aren't globally visible.



Consider the following code:



(function(){
var test = true;

})();


variable test is not visible anywhere else but within the function closure where it's defined.



What is a closure anyway?



Function closures make it possible for various scripts not to interfere with each other even though they define similarly named variables or private functions. Those privates are visible and accessible only within closure itself and not outside of it.



Check this code and read comments along with it:




// public part
var publicVar = 111;
var publicFunc = function(value) { alert(value); };
var publicObject = {
// no functions whatsoever
};

// closure part
(function(pubObj){

// private variables and functions
var closureVar = 222;
var closureFunc = function(value){
// call public func
publicFunc(value);
// alert private variable
alert(closureVar);
};

// add function to public object that accesses private functionality

pubObj.alertValues = closureFunc;

// mind the missing "var" which makes it a public variable
anotherPublic = 333;

})(publicObject);

// alert 111 & alert 222
publicObject.alertValues(publicVar);


// try to access varaibles
alert(publicVar); // alert 111
alert(anotherPublic); // alert 333
alert(typeof(closureVar)); // alert "undefined"


Here's a JSFiddle running code that displays data as indicated by comments in the upper code.



What it actually does?




As you already know this




  1. creates a function:



    function() { ... }

  2. and immediately executes it:



    (func)();


  3. this function may or may not accept additional parameters.




jQuery plugins are usually defined this way, by defining a function with one parameter that plugin manipulates within:



(function(paramName){ ... })(jQuery);


But the main idea is still the same: define a function closure with private definitions that can't directly be used outside of it.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...