what does () do at the end of the following code? [duplicate]
-
06-03-2021 - |
Question
Possible Duplicate:
What's the role of the parentheses in the following piece of code?
var dummy = (function (name) {return name;}(dummy || {}));
dummy.foo = ( function(s){
this.s = s;
return true;
}) ();
ok so I am not familiar with OO javascript but I know a little bit. Am I correct to say that this is the constructor for foo? what does the () do at the very end? also why is function(s){} in parentesis as well? there was some code in between but I took them out for simplicity sake. Would the above be the same as the below?
dummy.foo = function(s){
this.s = s;
return true;
};
I am trying to see what some code someone else wrote does and I don't have much experience in OO side so I am so confused as what's what. I can't even figure out which is the constructor
Solution
It's a self-executing JavaScript function:
http://briancrescimanno.com/2009/09/24/how-self-executing-anonymous-functions-work/
OTHER TIPS
var dummy = (function (name) {return name;}(dummy || {}));
This line passes the variable dummy
to the function, and returns it exactly; otherwise, it passes an empty object to the function. (The function is evaluated on-the-spot.) The value is then stored in the variable dummy
.
dummy.foo = ( function(s){
this.s = s;
return true;
}) ();
This defines the property foo
to the object dummy
. Currently, the function accepts an argument, which is stored to the property s
of the object dummy
. Currently, because it passes nothing to the function, it stores undefined
to the property s
.
The parenthesis at the end call the function just defined.
Here foo
is a function:
var foo = function (x) { return 2*x; };
Here bar
is a number (4 to be precise):
var bar = function (x) { return 2*x; } (2);