I was looking at some code to avoid using global variables and functions:
myNameSpace = function() {
var current = null;
function init() {
…
}
function change() {
…
}
function verify() {
…
}
return{
init:init,
set:change
}
}();
Call myNameSpace.set()
now will invoke the method change()
.
I have many doubts about the purpose of the last pair of parentheses, what are they used for?
What the two parentheses at the end do is execute the function that precedes them. That is, imagine the following:
what it does is assign a function (the implementation) to a function, so if we do
the function will be executed as it is being called (or to put it very informally, the parentheses have been added to it to execute it).
If we now go back to the code in your question, we have:
what happens is that the function is being defined and immediately it is being executed. This concept is known as self-executing functions (IIFE, " Immediately-invoked function expressions "), since as the name itself indicates, they are executed immediately after being defined.
Another very common way of seeing them is in the form:
But they both do the same thing, run the function.
Knowing that, if you go back to the original code, what those parentheses will do is immediately execute the function and assign myNamespace to the object returned by the return.
Short Answer
When doing
myNameSpace().set();
this, creating an object and executing the set method that you previously definedLong Answer
To understand what those parentheses do, let's separate the function and ask what type of data it is
myNameSpace
and what type of data it ismyNameSpace()
myNameSpace()
Its an object!!! , there are many ways to define Classes in JavaScript, this is one of them, but what if we put an example where it is easier to understand what happens when you executemyNameSpace().set()
@Sema has described it very well, although for readability to create a variable as a function it is usually used
myFunc = function(){ /* codigo */ }
, although they are both totally valid. If you want to wrap yourself in OOP, and you want to create an object with methods and attributes, then the current way you've commented would be the way to gomyNamespace = function(){ /* codigo */ }();
.When you do
set:change
, what this means is that itset
will have the function referencechange
, or in other words, itset
will point tochange
. Hence myNameSpace.set() executeschange()
, so since the contained valueset
is a function then the parentheses are needed()
to execute the referenced function.The following example is the same:
Although
fn2
it was not declared with the syntax of a function , it contains the reference of a function, so if you want to get the result, you will have to execute it as a function.