What does this line do?
var x = ( function() {
return "name";
}());
This is called an immediate function in Javascript. It looks like x will become a function, but in fact, it is assigned the value "name", the return value of executing the anonymous function.
Immediate functions are nice for one time work, such as setup, because (a) you won't have to create an object or function that lingers, as it is one time code, and (b) you protect the global scope from being written to, because all the variables in this functions are local.
Here is how to pass arguments to immediate functions
var x = ( function(arg1) {
return arg1 + "name";
}("my")); // returns "myname"
You can assign immediate fuction restuls to a property of an object such as in
var p = { name: ( function() {
return "aname";}() );
};
Finally, here is how to pass the global object to it, so you can still access global and you won't have to use 'window', which may not work if you are running the code in a non-browser environment
var x = ( function(global, arg1) {
return arg1 + "name";
}(this, "my")); // returns "myname"
References: Javascript patterns, Stoyan Stefanov
var x = ( function() {
return "name";
}());
This is called an immediate function in Javascript. It looks like x will become a function, but in fact, it is assigned the value "name", the return value of executing the anonymous function.
Immediate functions are nice for one time work, such as setup, because (a) you won't have to create an object or function that lingers, as it is one time code, and (b) you protect the global scope from being written to, because all the variables in this functions are local.
Here is how to pass arguments to immediate functions
var x = ( function(arg1) {
return arg1 + "name";
}("my")); // returns "myname"
You can assign immediate fuction restuls to a property of an object such as in
var p = { name: ( function() {
return "aname";}() );
};
Finally, here is how to pass the global object to it, so you can still access global and you won't have to use 'window', which may not work if you are running the code in a non-browser environment
var x = ( function(global, arg1) {
return arg1 + "name";
}(this, "my")); // returns "myname"
References: Javascript patterns, Stoyan Stefanov
Comments
Post a Comment