Self-executing anonymous function conventions [duplicate] - javascript

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.

Related

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.

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.

javascript module pattern implementations [duplicate]

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

What does function($) mean? [duplicate]

This question already has answers here:
What does function($) mean in javascript?
(3 answers)
Closed 9 years ago.
I just started learning JavaScript. Found a statement function($) { ...} while checking out examples. Can anyone tell me what function($) means?
It means "This defines a function. When it is called: create a local variable called $ and assign the value of the first argument to it."
First off: This creates a function where $ is the first argument passed to it. It could look like this potentially:
function dollar($){
alert($);
}
dollar("hello")
//alerts "hello"
Typically this is used when you want the $ to mean jQuery.
For example:
(function($){
//stuff where $ === jQuery
})(jQuery)
Means that jQuery will be passed into the $ variable for the scope of anything that happens in that function.
This can be useful if you have multiple libraries within the global scope that may use the $ variable, but you have a modular plugin that refers to the necessary library as that and you don't want to rewrite the whole thing.
Note: It does not always mean jQuery but in about 80% of cases it will. Otherwise it is just a convenient way to bind a library to a shorter variable within a certain scope.

difference between javascript function declaration [duplicate]

This question already has an answer here:
Anonymous function vs normal function
(1 answer)
Closed 9 years ago.
I know this type of question gets asked a lot, but I haven't seen any question with this type of declaration
(function(){
myFuncName=function(myVar){
// some logic
};
}());
how does that differ from
function myFuncName(myVar){
// some logic
}
The first one is an anonymous function and there is no way you can reference to and call it later on, so you just executes instantly ( ) once it had been created!
(function(){
alert(1)
}())
The second one is a reference function that you can call it anytime later. It wont gets executed unless you call it explicitly
What your doing is creating an anonymous function that also has a closure in it. Read more about closures here.
Basically a closure means that you have declared a function inside of another function. Which will let you access local variables after the first function exits.
Normally you would not be able to do this since they would be out of scope.
As for the other part. You can find a very useful guide to what's happening here Why do you need to invoke an anonymous function on the same line?.
To sum it up though, you have created an anonymous self-invoking function expression.
The self-invoking comes from the fact that () immediately follows the function expression.
Here's a link which explains the the function declarations in javascript.

Categories