javascript module pattern implementations [duplicate] - javascript

This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 9 years ago.
Is there any differences between javascript modules:
(function(){}())
vs
(function(){})()
First from book "good parts" by Crockford.
Second is code generated with Typescript.

There is no different. Also you can write the third option if your function doesn't return any value
!function(){}()

No, there is no difference between those two functions and how they're called. In both cases, you're creating an anonymous function and executing it immediately.
The only reason the "outer" parens are required is that when the JavaScript parser is expecting to see a statement, if it sees function it assumes what follows will be a function declaration. But we want to give a function expression, so by giving it an initial (, we put it into a state where it's expecting an expression.
But where the () to call the function go (after the } or outside the wrapping parens) doesn't make any difference.

No there is no difference, they both work the same. I tend to use the latter... it just seems to make more sense. (function(){}) defines the function and then you call it with (). In either case though, use a (leading)semicolon before the first (. Reference

Related

Meaning of !function in Javascript self invoking function [duplicate]

This question already has answers here:
What does the exclamation mark do before the function?
(8 answers)
Closed 5 years ago.
Sorry for posting this but !function is not google-able and I did not find it in my JavaScript code.
Here is how Twitter uses it:
Tweet
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
from https://twitter.com/about/resources/buttons#
It is short-hand or alternative of self-invoking anonymous function:
(function(){
// code
})();
Can be written:
!function(){
// code
}();
You can also use + instead of !.
If you simply did:
function(){
// code
}();
That will create problems, that's why you need to add ! before it which turns the function declaration into function expression.
Quoting docs, section 12.4:
An ExpressionStatement cannot start with the function keyword because
that might make it ambiguous with a FunctionDeclaration.
To better understand the concept, you should check out:
Function Declarations vs. Function Expressions
they're negating the result, not the function itself:
!function( x ){ return x }( true );
!true
false
In reality, it's a slightly compressed form of:
(function(){}())
since it requires 1 less character. The reason it's needed is that you can't call a function declaration directly, e.g. this is invalid:
function(){}()
but adding the ! at the beginning turns it into a function expression and makes it work.
It's usually used to work around a quirk in the JavaScript syntax. This gives a syntax error:
function() {
}();
It's read as a function declaration (like function foo () {}), rather than a function expression. So adding the ! before it, or wrapping it in parentheses, forces the parser to understand that it's an expression.

syntax for the module pattern in Javascript [duplicate]

This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 6 years ago.
I am learning module pattern in Javascript, and have come across these two ways to create a module:
var Module = (function () {
// code
})();
var Module = (function () {
// code
}());
is there a significant difference in these two approaches? if not, which is considered the better practice? Thanks.
Both are the same. The outer round braces are forcing the inside code to be evaluated as an expression. This means that in both cases the function code is treated as function-expression as well. And then this function is immediately executed due to () braces.
So, it should be exactly the same from the point of view of JS interpreter todo list: 1) get function expression, 2) execute it right away.
It only differs from aesthetic point of view - which way it looks more natural for you.

JavaScript function evaluating itself and calling itself at the same time [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 7 years ago.
I am learning about JavaScript functions on MDN
I came across an example that looks similar to this:
var saySomething = ( function(){console.log("hello")} )();
I have also seen this in the jQuery source.
I have not found any explanation of this style of function calling/definition on the MDN function reference.
I know from running the code that it calls itself immediately upon interpretation by the JavaScript engine.
Is this the Grouping Operator in action? Where it says:
First evaluate the body of this function and return it
Since the parentheses () immediately follow it it gets called ?
Google "Immediately Invoked Function Expression" or "IIFE".
The general syntax looks like this:
(function(){
// do something here
})():
Sometimes you'll see arguments passed in as well. It's basically used to wrap your code so none of your variables leak out into the global namespace.

Self-executing anonymous function conventions [duplicate]

This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 8 years ago.
Is there any difference between the following? Do they all work in the same way?
I've seen certain use-cases for .call() but I've never seen an explanation as to why the function call brackets are either inside or after the anonymous function declaration.
(function() {
}());
^^
(function() {
})();
^^
(function() {
}).call();
The first two are the same, and differ by style only*; the last one is different in that it gives you the ability to control what the value of this will be inside the IIFE. For example
(function(){
this.a = 12;
}).call(foo);
will add the property a to the object foo.
*Of course Douglas Crockford has a preference
The location of the () inside or outside the main () doesn't matter in the slightest. (Much) more discussion in this other question, but that question doesn't address the call option you raised.
call requires at least one argument according to the specification, so to be largely the same as your first two options, you'd want:
(function() {
}).call(undefined);
...to be sure some implementation doesn't get uppity with you for not supplying the argument.
I prefer 2nd way. JSLint uses the first way. You should always use .call() with an argument, so the third variant is wrong.
There is no difference between 1 and 2 though.

With jQuery, what is the point of encapsulating a function in round brackets? [duplicate]

This question already has answers here:
What is the purpose of a self executing function in javascript?
(21 answers)
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I see this in some HTML files that use jQuery, at the bottom:
(function() {
setTimeout(function(){window.scrollTo(0,0);},0);
})();
What does it mean to put the whole function in round brackets?
The code you gave as example is a self-executing anonymous function.
You can read more about them here.
Relevant text from that article:
What’s useful here is that JavaScript has function level scoping. All variables and functions defined within the anonymous function aren’t available to the code outside of it, effectively using closure to seal itself from the outside world.
(function() {})(); means it is self executing anonymous function. It get called immediately when java script get rendered. More details you can search it.
setTimeout is a function which accepts two parameters:
First parameter: A function
Second parameter: an integer value in milliseconds.
By calling the setTimeout function, the function from first parameter will be called/invoked after the amount of time specified in the second parameter.

Categories