Correct use of the module pattern syntax? - javascript

I've seen two ways...the first makes most sense to me.
Self execution parentheses are placed directly after the function brackets. All is included between parentheses to make it a function expression. Reference here
( function () {
// ... all vars and functions are in this scope only
// still maintains access to all globals
} () );
and this style, where self-execution parentheses are place after the parentheses which create the function expression. Reference here
var Var = ( function ( window, undefined )
{
} )();
I'm not sure if the var makes a difference in the syntax...?

The answer to your question is in the link about immediate functions in my first comment. Essentially, if you just want an immediate function, as long as the function declaration itself is wrapped in parentheses, it doesn't matter whether the calling parens follow the curly braces or follow the wrapping parentheses. However, if you don't want the wrapping parens, then the assignment to Var becomes relevant, as this will work:
var Var = function () {
// do stuff; return stuff;
}();
But this will not:
function () {
// do stuff;
}();
because it is only a function declaration followed by an unexpected pair of parentheses (a syntax error).

There's no difference between:
(function () {})();
and
(function () {}());
Douglas Crockford advocates for the second though (so JSLint will complain about the first style). He says the first is "counter-productive", whatever that means... I prefer the first.

It's actually 2 different patterns. The 2nd patterns is called the revealing module pattern as in it reveals some of the locals into the global namespace.

Related

Immediately invoked function expression invoking parenthesis [duplicate]

I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self executed.
The code used to wrap an anonymous function in parenthesis and then execute it,
(function () {
// code here
})();
but now it wraps the auto-executed function in parenthesis.
(function () {
// code here
}());
There is a comment by CMS in the accepted answer of Explain JavaScript’s encapsulated anonymous function syntax that “both: (function(){})(); and (function(){}()); are valid.”
I was wondering what the difference is? Does the former take up memory by leaving around a global, anonymous function? Where should the parenthesis be located?
They're virtually the same.
The first wraps parentheses around a function to make it a valid expression and invokes it. The result of the expression is undefined.
The second executes the function and the parentheses around the automatic invocation make it a valid expression. It also evaluates to undefined.
I don't think there's a "right" way of doing it, since the result of the expression is the same.
> function(){}()
SyntaxError: Unexpected token (
> (function(){})()
undefined
> (function(){return 'foo'})()
"foo"
> (function(){ return 'foo'}())
"foo"
In that case it doesn't matter. You are invoking an expression that resolves to a function in the first definition, and defining and immediately invoking a function in the second example. They're similar because the function expression in the first example is just the function definition.
There are other more obviously useful cases for invoking expressions that resolve to functions:
(foo || bar)()
There isn't any difference beyond the syntax.
Regarding your concerns about the second method of doing it:
Consider:
(function namedfunc () { ... }())
namedfunc will still not be in the global scope even though you provided the name. The same goes for anonymous functions. The only way to get it in that scope would be to assign it to a variable inside the parens.
((namedfunc = function namedfunc () { ... })())
The outer parens are unnecessary:
(namedfunc = function namedfunc () { ... })()
But you didn't want that global declaration anyways, did you?
So it it boils down to:
(function namedfunc () { ... })()
And you can reduce it even further: the name is unnecessary since it will never be used (unless your function is recursive.. and even then you could use arguments.callee)
(function () { ... })()
That's the way I think about it (may be incorrect, I haven't read the ECMAScript specification yet). Hope it helps.
The difference just exist because Douglas Crockford doesn't like the first style for IIFEs! (seriuosly) As you can see in this video!!.
The only reason for the existence of the extra wrapping () {in both styles} is to help make that section of code Function Expression, because Function Declaration cannot be immediately called. Some scripts / minify-ers just use +, !, - & ~ instead of too parentheses. Like this:
+function() {
var foo = 'bar';
}();
!function() {
var foo = 'bar';
}();
-function() {
var foo = 'bar';
}();
~function() {
var foo = 'bar';
}();
And all these are exactly the same as your alternatives. Choosing among these cases is completely on your own & makes no difference. { The ones with () produce 1 Byte larger File ;-) }

Different ways of defining self-executing javascript anonymous functions [duplicate]

I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self executed.
The code used to wrap an anonymous function in parenthesis and then execute it,
(function () {
// code here
})();
but now it wraps the auto-executed function in parenthesis.
(function () {
// code here
}());
There is a comment by CMS in the accepted answer of Explain JavaScript’s encapsulated anonymous function syntax that “both: (function(){})(); and (function(){}()); are valid.”
I was wondering what the difference is? Does the former take up memory by leaving around a global, anonymous function? Where should the parenthesis be located?
They're virtually the same.
The first wraps parentheses around a function to make it a valid expression and invokes it. The result of the expression is undefined.
The second executes the function and the parentheses around the automatic invocation make it a valid expression. It also evaluates to undefined.
I don't think there's a "right" way of doing it, since the result of the expression is the same.
> function(){}()
SyntaxError: Unexpected token (
> (function(){})()
undefined
> (function(){return 'foo'})()
"foo"
> (function(){ return 'foo'}())
"foo"
In that case it doesn't matter. You are invoking an expression that resolves to a function in the first definition, and defining and immediately invoking a function in the second example. They're similar because the function expression in the first example is just the function definition.
There are other more obviously useful cases for invoking expressions that resolve to functions:
(foo || bar)()
There isn't any difference beyond the syntax.
Regarding your concerns about the second method of doing it:
Consider:
(function namedfunc () { ... }())
namedfunc will still not be in the global scope even though you provided the name. The same goes for anonymous functions. The only way to get it in that scope would be to assign it to a variable inside the parens.
((namedfunc = function namedfunc () { ... })())
The outer parens are unnecessary:
(namedfunc = function namedfunc () { ... })()
But you didn't want that global declaration anyways, did you?
So it it boils down to:
(function namedfunc () { ... })()
And you can reduce it even further: the name is unnecessary since it will never be used (unless your function is recursive.. and even then you could use arguments.callee)
(function () { ... })()
That's the way I think about it (may be incorrect, I haven't read the ECMAScript specification yet). Hope it helps.
The difference just exist because Douglas Crockford doesn't like the first style for IIFEs! (seriuosly) As you can see in this video!!.
The only reason for the existence of the extra wrapping () {in both styles} is to help make that section of code Function Expression, because Function Declaration cannot be immediately called. Some scripts / minify-ers just use +, !, - & ~ instead of too parentheses. Like this:
+function() {
var foo = 'bar';
}();
!function() {
var foo = 'bar';
}();
-function() {
var foo = 'bar';
}();
~function() {
var foo = 'bar';
}();
And all these are exactly the same as your alternatives. Choosing among these cases is completely on your own & makes no difference. { The ones with () produce 1 Byte larger File ;-) }

What is difference between (function(){}()) and (function(){})()? [duplicate]

I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self executed.
The code used to wrap an anonymous function in parenthesis and then execute it,
(function () {
// code here
})();
but now it wraps the auto-executed function in parenthesis.
(function () {
// code here
}());
There is a comment by CMS in the accepted answer of Explain JavaScript’s encapsulated anonymous function syntax that “both: (function(){})(); and (function(){}()); are valid.”
I was wondering what the difference is? Does the former take up memory by leaving around a global, anonymous function? Where should the parenthesis be located?
They're virtually the same.
The first wraps parentheses around a function to make it a valid expression and invokes it. The result of the expression is undefined.
The second executes the function and the parentheses around the automatic invocation make it a valid expression. It also evaluates to undefined.
I don't think there's a "right" way of doing it, since the result of the expression is the same.
> function(){}()
SyntaxError: Unexpected token (
> (function(){})()
undefined
> (function(){return 'foo'})()
"foo"
> (function(){ return 'foo'}())
"foo"
In that case it doesn't matter. You are invoking an expression that resolves to a function in the first definition, and defining and immediately invoking a function in the second example. They're similar because the function expression in the first example is just the function definition.
There are other more obviously useful cases for invoking expressions that resolve to functions:
(foo || bar)()
There isn't any difference beyond the syntax.
Regarding your concerns about the second method of doing it:
Consider:
(function namedfunc () { ... }())
namedfunc will still not be in the global scope even though you provided the name. The same goes for anonymous functions. The only way to get it in that scope would be to assign it to a variable inside the parens.
((namedfunc = function namedfunc () { ... })())
The outer parens are unnecessary:
(namedfunc = function namedfunc () { ... })()
But you didn't want that global declaration anyways, did you?
So it it boils down to:
(function namedfunc () { ... })()
And you can reduce it even further: the name is unnecessary since it will never be used (unless your function is recursive.. and even then you could use arguments.callee)
(function () { ... })()
That's the way I think about it (may be incorrect, I haven't read the ECMAScript specification yet). Hope it helps.
The difference just exist because Douglas Crockford doesn't like the first style for IIFEs! (seriuosly) As you can see in this video!!.
The only reason for the existence of the extra wrapping () {in both styles} is to help make that section of code Function Expression, because Function Declaration cannot be immediately called. Some scripts / minify-ers just use +, !, - & ~ instead of too parentheses. Like this:
+function() {
var foo = 'bar';
}();
!function() {
var foo = 'bar';
}();
-function() {
var foo = 'bar';
}();
~function() {
var foo = 'bar';
}();
And all these are exactly the same as your alternatives. Choosing among these cases is completely on your own & makes no difference. { The ones with () produce 1 Byte larger File ;-) }

Should function call go before or after brackets that wrap function body? [duplicate]

I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self executed.
The code used to wrap an anonymous function in parenthesis and then execute it,
(function () {
// code here
})();
but now it wraps the auto-executed function in parenthesis.
(function () {
// code here
}());
There is a comment by CMS in the accepted answer of Explain JavaScript’s encapsulated anonymous function syntax that “both: (function(){})(); and (function(){}()); are valid.”
I was wondering what the difference is? Does the former take up memory by leaving around a global, anonymous function? Where should the parenthesis be located?
They're virtually the same.
The first wraps parentheses around a function to make it a valid expression and invokes it. The result of the expression is undefined.
The second executes the function and the parentheses around the automatic invocation make it a valid expression. It also evaluates to undefined.
I don't think there's a "right" way of doing it, since the result of the expression is the same.
> function(){}()
SyntaxError: Unexpected token (
> (function(){})()
undefined
> (function(){return 'foo'})()
"foo"
> (function(){ return 'foo'}())
"foo"
In that case it doesn't matter. You are invoking an expression that resolves to a function in the first definition, and defining and immediately invoking a function in the second example. They're similar because the function expression in the first example is just the function definition.
There are other more obviously useful cases for invoking expressions that resolve to functions:
(foo || bar)()
There isn't any difference beyond the syntax.
Regarding your concerns about the second method of doing it:
Consider:
(function namedfunc () { ... }())
namedfunc will still not be in the global scope even though you provided the name. The same goes for anonymous functions. The only way to get it in that scope would be to assign it to a variable inside the parens.
((namedfunc = function namedfunc () { ... })())
The outer parens are unnecessary:
(namedfunc = function namedfunc () { ... })()
But you didn't want that global declaration anyways, did you?
So it it boils down to:
(function namedfunc () { ... })()
And you can reduce it even further: the name is unnecessary since it will never be used (unless your function is recursive.. and even then you could use arguments.callee)
(function () { ... })()
That's the way I think about it (may be incorrect, I haven't read the ECMAScript specification yet). Hope it helps.
The difference just exist because Douglas Crockford doesn't like the first style for IIFEs! (seriuosly) As you can see in this video!!.
The only reason for the existence of the extra wrapping () {in both styles} is to help make that section of code Function Expression, because Function Declaration cannot be immediately called. Some scripts / minify-ers just use +, !, - & ~ instead of too parentheses. Like this:
+function() {
var foo = 'bar';
}();
!function() {
var foo = 'bar';
}();
-function() {
var foo = 'bar';
}();
~function() {
var foo = 'bar';
}();
And all these are exactly the same as your alternatives. Choosing among these cases is completely on your own & makes no difference. { The ones with () produce 1 Byte larger File ;-) }

Purpose of the outer extra parenthese on JavaScript closure function [duplicate]

This question already has answers here:
JavaScript - self-executing anonymous functions and callback
(2 answers)
Closed 9 years ago.
What is the purpose of the outer extra parentheses on the below JavaScript closure function? I have been told in other posts that they are not strictly necessary, but they're a convention to make it clear that the result of the function is being passed, not the function itself. The below quote from http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html
, however, conflicts. Which is correct?
Notice the () around the anonymous function. This is required by the
language, since statements that begin with the token function are
always considered to be function declarations. Including () creates a
function expression instead.
(function () {
// ... all vars and functions are in this scope only
// still maintains access to all globals
}());
I think that different engines have different ways of interpreting
function(){...}();
so the most popular and accepted way to make it clear, to all engines, is to group the code in parentheses.
(function(){...}());
At the same time, what you quoted makes a very interesting point. A function expression might go:
var f = function() {...}
Whereas a function declaration looks like:
function f() {...}
You see how it's easy/convenient for the parser to tell the difference by looking at the first token?
IF TOKEN1 EQ "function": FXN DECLARATION
ELSE: FXN EXPRESSION
But it wouldn't make sense for your (immediately-invoked) function to be a function declaration (it's not going to be re-used, you don't want to have it hoisted, or in the namespace, etc.) so adding some innocuous parentheses is a good way of indicating that it's a function expression.
First of all, I must clear up:
(function () {
}());
is equivalent for
(function () {
})();
and also for (Backbone.js uses it)
(function(){
}).call(this);
Second, if you're going to use it that way, then it's not an anonymous/closure function. its Immediately-Invoked Function expression
it would act as a closure (because it won't be immediately-invoked) if you assign its returned context to a variable. This kinda useful if you need a static class (when properties and methods could be accessed without instantiation). For example:
var stuff = (function(){
// AGAIN: its not an IIFE in this case
function foo() // <- public method
{
alert('Jeeez');
}
return {
foo : foo,
}
})();
stuff.foo(); //Alerts Jeeez
What is the purpose of the outer extra parentheses on the below
JavaScript closure function?
The purpose isn't usual and quite strange - its all about function arguments.
For example,
(function(window, document){ // <- you see this? 2 "arguments"
alert(arguments.length); // 0!
})();
but if we pass them to that outer parentheses
(function(/* So its not for arguments */ ){
alert(arguments.length); // 2
})(window, document); // <- Instead we pass arguments here
The extra surrounding parentheses disambiguate a function expression from a regular function declaration.
Though the extra parentheses are standard practice, the same thing can be achieved by doing this instead:
void function() {
// do stuff
}();
Or, even:
+function() {
// do stuff
}();
Though, out of these two alternatives, I prefer the void notation because in most cases we don't really care about the return value of an immediate invocation.
Other places where the parentheses aren't required is when an expression is expected:
setTimeout(function() {
return function() {
alert('hello');
}
}(), 1000);
They are necessary because the parser goes in the function declaration mode when it sees
function
in a statement context.
After function token, it is expecting a name for the function because a function declaration must include a name for the function. But instead of a name it sees ( instead, so it's a syntax error.
I think, it could backtrack and unambiguously just treat it as a function expression but it doesn't.
var module = XXX
In the above, XXX is in expression context, if a function appears there, it is treated as a start of a function expression. Function expressions don't have to have
a name for the function, so it's not a syntax error to have ( appear right after function.
So you can write:
var module = function(){}();
But not
function(){}()
You can use many tricks to make the above an expression:
(XXX)
!XXX
~XXX
+XXX
//This doesn't work however:
{YYY} //the braces are delimiting a block, and inside block you start in
//a statement context
XXX is in expression context because it's enclosed by parenthesis or is following a unary operator, therefore any function substituted for XXX is a function expression.

Categories

Resources