What does this block of JS code mean? [duplicate] - javascript

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);

Related

Unable to understand certain concepts in JavaScript

In the website the following lines are given:
Your global variables (or functions) can overwrite window variables (or functions).
Any function, including the window object, can overwrite your global variables and functions.
I am unable to understand what this says.
Above that paragraph you can find this:
Global Variables in HTML
With JavaScript, the global scope is the complete JavaScript environment.
In HTML, the global scope is the window object. All global variables belong to the window object.
Combined with the quote in your question - it means that because the global scope is actually the window object - it's possible to override global functions/variables.
Here is an example:
console.log(window.Math.PI);
Math = {
PI: 5
}
console.log(Math.PI);
The browser puts certain "global" (i.e. accessible anywhere in any file) functions and variables on the window object. One such example is the function window.setTimeout, which executes its argument after a given delay.
You can also access these global window.* variables without the window prefix at all, i.e.
window.setTimeout === setTimeout
That means if you assign to a global variable with a conflicting name, you can 'override' the browser defaults -
window.setTimeout === setTimeout
setTimeout = 'myString'
window.setTimeout === 'myString'
That's why it's generally best practice not to create variables in the global (window) scope.

Javascript syntax seen in SignalR

When learning the SignalR, I see some JS script pattern like below in the auto-generated hubs script. What's this syntax?
(function(a,b,c){...}(e,f));
Or in the hubs:
(function($, window, undefined){...}(window.jQuery, window));
That is called a self-executing function. It basically declares the function code and then calls it immediately passing in the parameters that you see after the function. In the case of the hubs method it is passing in the window.jQuery object to the '$' parameter, the global window object to the 'window' parameter and omitting the third parameter which will assign a value of 'undefined' to the third parameter. All of that code is wrapped in a closure.
Using all of the code in a closure typically keeps the code within the closure separate (or private) within the scope of the closure and helps to prevent polluting the global namespace (the window object).
I am not an expert in JS but I think that with this syntax you define the function and then you call it with the parameters (window.jQuery, window)

Memory consumption by anonymous function in javascript

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.

What does the global in (function(global){ some code .. })(this) do?

I was looking at adding comments to JSON and found this script that strips them out before processing making the JSON valid. I am just trying to understand how it works to make the JSON.minify() function available?
It starts with
(function(global){ ...
totally which is weird to me. I found that "global is a property of a RegExp instance, not the RegExp object" on MDN but I don't understand how it is works in this script if at all.
This snippet:
(function(global){
// your code here
// referring to the variable named "global" in this scope
// will be a reference to the default javascript global object
})(this);
is a construct for assigning the global object (whatever it might be) to an argument labeled global for all code that is inside this self-executing function.
The self executing function is used to define a separate execution scope so that any functions or variables you define inside this other scope will not interfere with or be directly accessible from outside this scope (insulating your scope from other code scopes).
In a browser, the global object is the window object, but if you intended to have code that might work in other javascript environments (like no node.js on a server) where the global object might not be window, this is a way of extracting the global value from the default this value, putting it into another variable which you can then refer to anywhere inside your code block.
For code mean to only run in a browser, there really is no point to this. You can just refer to window when you need the global object.
It's just a function parameter name. It might as well be froozboggles.
This code:
(function(foo) {
// In here, what's called "bar" in the outer scope is called "foo"
})(bar);
Defines an anonymous function taking one parameter bar and immediately calls it with the value of bar as the first parameter.
Apart from what jfriend00 mentions in his fine answer, it's also a good way of making sure that you don't leak variables and functions to the outer scope: If you declare, say, var baz = 17; in the top scope in javascript, it will be a property of window. If you wrap it in a function as in the pattern you mention, you can only export properties to window explicitly -- by assigning them to global, in the case of your example. Edit: As #josh3736 says in his comment, you can also leak to window by assigning without a previous declaration, e.g. quux = 4711;.

What is and how to determine the calling context of an invoked method or function within another function?

What is the calling context of an invoked method or function within another function?
In browsers, the default calling context is the window object. In various situations, how do I avoid this?
If a function is invoked -- for example, by theFunction(); -- within a containing function, is the invoked function's calling context the containing function?
In these two examples
(function ()
{
something.initialize();
}());
and
(function ()
{
something.initialize.call(this);
}());
..., is the calling context the same?
They are not the same. In the following I assume you were talking about this when you mentioned context.
In the first example, inside initialize, this will refer to something. In the second one, it will refer to the global object, which is window in browsers.
What this refers to is determined by how the function was called. There are five cases:
func(), calling a function "standalone": this refers to the global object.
new func(), calling a function as constructor method: this will refer to an empty object which inherits from func.prototype.
obj.func(), calling a function as property of an object: this will refer to the object obj.
func.apply(foo), func.call(foo), invoking a function with apply or call: this refers to the object passed as first argument.
ECMAScript 5 also introduced .bind() [MDN] which enables you to bind this to a certain object, without immediately calling the function.
Now you understand why in your second example, inside initialize, this will refer to window:
The outer function is called "standalone" (first case), so this inside of it will refer to window. Next you are passing this to call, which sets this inside initialize to window (fourth case).
Further reading:
MDN - this, explains all I write above with some examples.
No, they are not the same. The first parameter to the call method sets the value of this inside that function; example 1's this should theoretically contain a reference to something; example 2's this corresponds to the this of your self executing function.
The environment available to a function when it is invoked is based on several things.
the this binding which is different for the initialize method in your example
the actual parameter bindings which are not and a binding for a special arguments object
a binding for the function name, if any
the environment chain at the time the function was created. This is the "close" part of the term "closure". A javascript function "closes over" all the variables that are in-scope when the function object comes into existence.
In your example, only 1 is affected by the choice to use call which has the effect of passing this instead of something as the this value in the method body.
The relevant part of the spec starts at section 10.4.3
The following steps are performed when control enters the execution context for function code contained in function object F, a caller provided thisArg, and a caller provided argumentsList: ...
Functions don't create context, unless it's a constructor (a function called with new).
In your second example the context is undefined (which gets transformed into the global object , window). In ES5 strict mode it won't be transformed into anything.
I recommend John Resig's interactive JavaScript tutorial on the topic of context.

Categories