This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Explain JavaScript’s encapsulated anonymous function syntax
i don't understand completely what this does, so i wanted to look it up in google but I didn't find anything and realized that I don't know its name; so my question is: What is the name of this construction (?) :
( function ( ... ) {} )( jQuery, window, document );
Thanks in advance guys.
It is a Self Executing Anonymous Function, or Immediately Invoked Function Expression (IIFE), as others also answered.
It's called a Self Executing Anonymous Function.
The purpose is to control scope so you aren't referencing globals or poluting the global namespace.
It's an Self Executing Anonymous Function.
You can use these to prevent polluting or accessing the global (window) namespace with new vars.
Related
This question already has answers here:
What is the use of the JavaScript 'bind' method?
(23 answers)
Closed 7 years ago.
Met the code first time:
var Controller = function($scope){
this._scope = $scope;
}
Controller.$inject = ['$scope'];
Controller.prototype.augmentScope = function() {
this._scope.a = {
methodA: this.methodA.bind(this)
}
}
I really don't understand what is the point. Any explanations?
It assumes that in the closure scope (If none it will be in the global scope such as window) there is a method called methodA. Then again, because the this is really the enclosing scope mentioned), it will remind it and assign it ti be used be through object a as well.
So you can execute it by:methodA() or a.methodA()
Edit to explain closure:
Although Javascript is very similar to Java/C++ in syntax it's quite different than both of them in the sense that when a function is instantiated as an object, it remembers the scope it was instantiated in. I would highly recommend anyone doing more than the casual JS(if there is such a thing), to look into this article.
The this in JS will deffer depends if it was created inside an instantiated function - AKA: new MyClass(). Referring to a literal object such as:
var myObj={a:this.b}
will not create a new this and will by default refer to enclosing scope. If none was created it will be the global object such as window in a browser
This question already has answers here:
How does this JavaScript/jQuery syntax work: (function( window, undefined ) { })(window)?
(5 answers)
Closed 8 years ago.
I am using my js files like:
(function() {
'use strict';
angular
.module('app.someModule')
.config(config);
function config(someDependency){
//some configuration
}
config.$inject=['someDependency'];
})();
However I saw when i using closures some people injects the angular object itself the closure. Something like:
(function(angular){/*whatever logic*/})(angular);
Which one is a better usage or Are there any difference between two usage?
So I dont add global angular variable as always that don't cause any trouble?
The difference between two immediately executed functions (IIFE) is that in the second case you invoke function with one parameter angular. The benefit it can give is slightly improved performance as there is no need for Javascript engine to look up for a variable in global scope, as the angular object is available in local closure scope as a reference passed with function invocation (but of course it still points to the same Angular object, defined in global scope).
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.
This question already has answers here:
What does (function($) {})(jQuery); mean?
(6 answers)
Closed 9 years ago.
; (function ($, undefined)
{
// all the variables and functions of the js document
})(jQuery);
I've seen this twice now in the jquery/javascript files for a zoom script. I don't understand what this is exactly. I can't seem to google it, I don't remember coming across this on tizag or w3schools while recently learning jquery and js.
There's nothing before or after this code (other than some comments). So I'm utterly lost as to what (function())(jQuery); is or does.
(function ($, undefined)
{
// all the variables and functions of the js document
})(jQuery);
calls a block of code ensuring that inside
$ is usable to refer to jQuery
undefined is undefined (edit: this was useful because undefined could be redefined at that time in the oldest browsers, it's now useless)
and that any minifier can change undefined to a shorter label.
The initial ; ensures you can concatenate this file with another one : without this, you'd have an error executing the concatened file if the one just before was something like
(function (){
})()
This is a way to ensure that $ is indeed the jQuery object and to ensure that any local variables and methods are privately scoped, that is, do not pollute the global namespace.
It is a self-calling anonymous function, with the parameter passed being jQuery, meaning that the $ will be the jQuery object.
Being declared inside a function means that the inner variables and methods will not be visible outside of it.
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.