As soon as the function is declared wth function keyword javascript assigns a block of memory to the function name where function itself gets stored.
function maiz(){}
console.log(maiz);//output:function maiz(){}
but what will js do when function is declared anonymous or where will the anonymous function gets stored
(function (){})()
As soon as function is declared there should be some memory to store even the annonymos function and than execute it.Am i wrong?
You cannot declare an anonymous function. What you can do is have an anonymous function expression, which means you feed the function object somewhere (assignment, function call argument, etc). See Kangax' article or this question for the difference.
So if you want to know where an anonymous function expression goes to (in the memory), you will have to look at the surrounding statements. This one for example:
(function (){});
would immediately after it has been instantiated be vanished by the garbage collector. And if you have
(function (){})();
then the code inside will be executed (in a new scope), but the function itself will not get stored anywhere as well. Btw, this construct is called an immediately-invoked function expression (IIFE).
Anonymous functions are better explained in the book Secrets of the JavaScript Ninja(John Resig)
We can declare an anonymous function as a property of an object.
var ninja = {
shout: function(){ // shout property now referenced to anonymous function
assert(true,"Ninja");
}
};
Anonymous functions are typically used in cases where we wish to
create a function for later use, such as storing it in a variable,
establishing it as a method of an object, or using it as a callback
(for example, as a timeout or event handler). In all of these
situations, the function doesn’t need to have a name for later
reference.
If there’s no need for a function to be referenced by its name, we don’t have to give it one (Anonymous function). It behaves as actual function which has name. But it doesn't have name. So Anonymous functions are stored where javascript functions are stored.
Related
Can somebody explain me what (this) means at the end of the following code:
var a=(function(_this){
return function() {
//do something
return smth;
};
})(this);
What is the sense of such coding?
Going forward, what does the following code do, when placed in .js file and invoked by html tag?
(function() {
Emitter=(function(){
function Emitter() {}
...
return Emitter;
})();
A=(function(_super){...})(Emitter);
}).call(this);
how to instantiate object A from outside the js file?
This is a self-executing function, which is used to save a reference to "this" through the function's closure. It is used to hold on to the reference to "this" at the function's first execution time.
You can also use Function.prototype.bind() to achieve a similar result of saving a reference to "this":
MDN - Bind
This whole structure is a means of saving the current value of this so that a function call later on can use it.
That could all be done also with .bind() like this which (if you understand what .bind() does might be easier to follow):
function myFunc(_this) {
// do something
}
var a = myFunc.bind(null, this);
Here are the various steps in what happens in the code you've shown:
this will have a value from the surrounding context when this code is originally executed (which you don't show). It is being passed into a self-executing function as an argument often referred to as an IIFE (immediately invoked function expression) which is just a function call that happens immediately inline as the code is initially run.
Within that function it is given an argument name of _this.
When that function executes, it returns another function. The body of that inner function also has access to _this.
When that inner function is returned, it is assigned to the variable a.
The upshot of all this is that one can call a() and the internals of that function, when it executes will be able to access _this which contains the value of the original this.
So, it's essentially a means of creating a function that when executed will have access to the original value of this even though the context will have changed when a() is later called. So, its essentially saving the value of this for a specific function to use later.
More detail would require more context about what is going on inside that internal function, what the this value was in the original context and how a() is used later.
This is one particular use of an IIFE. They have many other uses.
When I make an anonymous function in JavaScript like this:
(function(){
/* some code here */
})()
In which object will be this function added, and where will this function live?
Also you can see in the jQuery source code an anonymous function like this:
(function(window, undefined){
/* some code here */
})(window)
How do this function's arguments differentiate it from an anonymous, 0-arg function?
Functions in JavaScript are values. That is, a function is represented by an object, and like any other object it can be the value of a variable or participate in expressions.
Thus
(function() { ... })
is a value, just like 17 or "hello world" is a value.
When a function (as a value) appears in an expression, and it's followed by (...) with a comma-separated list of expressions between the parentheses, that's a function call.
OK, so:
(function() { ... })()
creates a function (as a value) and then invokes that function with no arguments. The function object, at least as a direct result of that code, is not stored anywhere. It essentially vanishes after the function call completes, and the overall value of that subexpression will be whatever the function returned.
Passing parameters to such a function is no different than passing parameters to any other function. In the specific example you quote, the purpose is to prevent certain kinds of anomalies caused by errant "alien" code. Your example really should read:
(function(window, undefined) {
// code
})(this);
The symbol this is a reserved word and its value is under complete control of the runtime. (Well, it's value in a local execution context is thusly controlled.) When evaluated in the global scope, the above code ensures that inside the anonymous function, the symbol "window" will be a reference to the global context. That sort of construct is also useful for code that may be used in contexts other than a browser, like Node.js for example, where the global context isn't called "window".
Both examples you gave are anonymous functions, according to the first line of the Wikipedia definition:
an anonymous function [...] is a function (or a subroutine) defined, and possibly called, without being bound to an identifier
The arguments do not make a difference with respect to anonymity. Anonymous functions can take 0, 1, 2, ... n arguments, just like non-anonymous functions (i.e. named functions).
One major advantage of anonymous functions is that they don't have to live anywhere -- they can be defined and used inline, just like other values of other types.
Adding to #Pointy's answer adding parameters to an anonymous function doesn't make any difference
(function(){
/* some code here */
})()
(function(window,undefined){
/* some code here */
})(window)
Both the functions are lost after they are called, the only difference is that inside the second function some variables or functions are being stored in window context, but the anonymous function in itself is lost after the call.
If you need to keep the reference to the function try
(window.myFunc = function(arg1, arg2, arg3) {
/* your code here*/
})(arg1, arg2, arg3)
Based on some code in a lecture by Doug Crockford, I've created this.
var isAlphaUser = (function() {
alert("Forming Alpha User List");
let AlphaUsers = {
1234: true,
5678: true
};
return function(id){
alert("Checking Alpha Users:",id);
return AlphaUsers[id];};
}());
alert("starting");
alert(isAlphaUser(1234));
alert(isAlphaUser(5678));
alert(isAlphaUser(3456));
which gives me this:
Forming Alpha User List
starting
Checking Alpha Users: 1234
true
Checking Alpha Users: 5678
true
Checking Alpha Users: 3456
undefined
Which is quite cool, as it does the expensive setup once only, and every further call is a cheap check.
However, I can't decipher the code that does this. Specifically, I can't understand why I need the "()" at the end of the function declaration.
Can somebody explain how this syntax is working?
() calls a function. function() { } defines a function. Appending () right after immediately calls it1, and the result (also an anonymous function) is assigned to isAlphaUser.
The function() { ... }() pattern is frequently used to isolate variables to an inner scope, so those variables don't become part of the global scope.
In this case, this is what happens:
An anonymous function is run, defining a variable AlphaUsers inside that scope.
That function returns another function that takes 1 parameter. This function is a closure to which the AlphaUsers variable becomes bound (in other words, available). This function checks if the parameter passed in is contained in AlphaUsers (actually, it returns the item at that index, which is just a boolean).
The return value is assigned to a variable isAlphaUser.
Since isAlphaUser is now a function, it can be called to see if the parameter is contained in the AlphaUsers variable, but no direct access to AlphaUsers is available in the global scope (it become a sort of private variable).
1 — Note: As cwolves mentioned in the comments, beware that while () appended directly after the } works in this case, it is only because in this case the function definition is a function expression. If function is the first word on the line, the line becomes a function declaration, and that is all that line can do, the function is not anonymous (it will require a name, otherwise it's a syntax error) and cannot be called immediately inline. See Function Declarations vs. Function Expressions for more info.
The () at the end of the code is separate from the closure issue. By wrapping your function in parens and adding the () at the end you are creating an anonymous function that is run immediately with whatever arguments you pass into ().
Specifically, I can't understand why I need the "()" at the end of the
function declaration.
It creates self-invoking function, in other words, the function is executed as soon as it is parsed.
It is basically same thing when you call a function by suffixing it with () like:
myfunc(); // call this func
The top-level anonymous function returns the function that the isAlphasUser varaible refers to.
You need to call the top-level function, to get the inner-function reference.
Think of it like this, the outer anonymous function is a function factory, i.e., it returns a function.
In order to use any function (even one that returns a function) you must call it.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
I came across a JS file that can be summarized to the code below:
(function(window){
// some codes here
})(window);
I wonder what this block of code means? Has the window special meanings, or it is just a parameter? What are the differences between the two "window" we see in the brackets?
Since this function does not have a name, I assume it is an anonymous function, so is it only invoked once? When is it invoked?
This is called a immediately-invoked anonymous function. (IIAF for short.)
In this case, you are defining a function that takes in a parameter called "window" that overrides the global window object inside of that scope.
The kicker here is that right after defining the function, you're immediately invoking it, passing in the global window object, so it is as if you used the global reference within the function closure!
Most of the time, the purpose of this is to avoid polluting the global namespace by way of wrapping all potential variables within an anonymous scope.
As far your questions regarding window, the window in parentheses at the bottom is a reference to the global window object. The first window is just a name for a parameter. But in this instance it refers to the global window object since you're using an anonymous self-invoked function. You could call it monkeys and it wouldn't make a difference (of course, you'd have to use monkeys within the body of the anonymous function then, to refer to the parameter). So now, you now have a reference to the global window object within your function.
Yes, the function is invoked once and it is invoked as soon as it is defined. This is because it is a self-invoked anonymous function.
It's a closure. The code in question is a an anonymous function, which will execute with the "window" parameter (end of your snippet). It won't pollute the global namespace.
The first window is formal parameter, while the second one is actual parameter that actually invokes the function. This type of function called self-invoking functions.
The benefit of it is that wrapping functions this way doesn't clutter global scope..
It is an immediately invoked function expression. the grouping operator () around a function expression (essentially a function declaration without a name) means that the enclosed function is evaluated and a function object returned. A function followed by a formal parameter list (another set of ()) causes the function to be called, so:
(function() {
alert('hey');
})();
creates an anonymous function that is called immediately and run once. It doesn't create any global variables and leaves no trace of its existence.
Passing the indentifier window to the function means that it is passes whatever it references. The presumption here (I suppose) is that it will reference a global window object that, in browsers, is the global object. However, in an environment that doesn't have a global window object, it may well be undefined. It is a pointless exercise in my view.
If you are concerned about getting a refernce to the global object, then pass this from the global context:
(function(global) {
// global refernces the global object
})(this);
The book Learning JavaScript defines anonymous functions as follows...
Functions are objects. As such, you can create them - just like a String or Array or other type - by using a constructor and assigning the function to a variable. In the following code, a new function is created using the Function constructor, with the function body and argument passed in as arguments:
var sayHi = new Function("toWhom", "alert('Hi' + toWhom);");
This type of function is often referred to as an anonymous function because the function itself isn't directly declared or named.
Is this the correct definition of an "anonymous function" in JavaScript? If not, what is an anonymous function, and is there any difference between an anonymous function and a function literal?
Function expressions and function declarations
Since you are interested in functions, here is some important stuff to know.
var abc = function() { ... } is known as a function expression. The variable will be assigned that anonymous function at execution time, though its variable declaration will be hoisted to the top of the current execution context (scope).
However, a function expression can be given a name too, so that it can be called within its body to make it recursive. Keep in mind IE has some issues with this. When you assign it a name, it is most definitely not an anonymous function.
A function such as function abc() { ... } is known as a function declaration. Its definition is hoisted to the top of its scope. Its name is available within it and its parent's scope.
Further Reading.
Your Example
It is an anonymous function, but assigned to the variable sayHi.
As Šime Vidas mentions, a new Function object is instantiated with the new operator, and the arguments and function body are passed in as strings. The resulting object is assigned to sayHi.
The real world use of creating a function using this method is rare (though it may be just to help show that functions are objects). I also believe passing its arguments list and function body as a string will invoke an eval() type function, which is rarely good when a much better construct is available.
Also, functions created with Function do not form a closure.
I would only use this method if for some reason I needed to create a Function with its arguments and/or body only available to me as a string.
In the real world, you'd do...
var sayHi = function(toWhom) {
alert('Hi' + toWhom);
};
Also refer to comments by Felix and Šime for good discussion and further clarification.
I think a broader and more accepted definition of an anonymous function is a function that is created without a name.
An anonymous function is simply a function with no name.
function(a, b){
return a + b;
}
The above code would be useless as it has no name to which you could call it with. So they are usually assigned to a variable.
var func = function(a, b){
return a + b;
}
This is helpful because you can pass an anonymous function to another function or method without having to create the function before hand, as demonstrated below.
function bob(a){
alert(a());
}
bob(function(){
return 10*10;
})
This:
new Function("toWhom", "alert('Hi' + toWhom);")
and this:
function(toWhom) { alert('Hi' + toWhom); }
are two expressions that produce the same result - they return a new anonymous function object.
The second expression (and only the second expression) is called a function expression. You may also call it a function literal (although we could argue that a function declaration is also a function literal).
function foo(){
alert("i'm foo, nice to meet you!");
}
var bar = function(){
alert("I am an anonymous function assigned to the variable \"bar\"");
}