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)
Related
I see some self executing function, where the global variable is passed as an argument, even though the global variables are accessible inside the function.
var MyApp = {};
(function(app) {
//Do something with app varaible.
})(MyApp);
is there any reason to pass them to the functions through arguments?
Function arguments, as well as variables declared with var inside the scope of the function, are scoped locally and shadow any values for the same variable in outer scopes.
In your example, this allows $ to have a value outside of the function, and it is only temporarily switched to the jQuery object while inside the function.
$ = "stuff";
console.log($); // "stuff"
(function($) {
console.log($); // the jQuery object
})(jQuery);
console.log($); // "stuff"
Considering your initial code with jQuery:
Is just to help writing code, some programmers get addicted to the $ so they pass the jQuery as arguments and call it $. That code is a better way of doing this $=jQuery, in codes where other frameworks already user $, $=jQuery would overwrite other API code... You typically see that kind of code construct when you use jQuery along with other conflicting libraries that forced you to call jQuery.noConflict().
jQuery.noConflict() removes you the $ functions where you previously were able to do this $('div')... so to keep using $ as before, in code where you know that $ should mean jQuery then you declare code like:
(function($){
...
})(jQuery);
About the closures in general:
This is useful in other cases, imagine you have huge function working using the jquery $ variable and then you add a library to your project that conflicts with $, the closure above would help you in not re-write the code, you could wrap it inside the closure an user $ inside.
Just one more thing, for clearness, (function(){})() is called a closure because you declare an anonymous function an then you execute it, which means you create a private context inside that function.
link about closures: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
The why for passing globals as parameter to closures, is because when you pass the globals as parameters to locals you rename that global to another name inside of the closures context only. This is a controlled way of saying "hey here jQuery is called $ and jQuery".
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;.
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);
jQuery starts off wrapping all of it's code in an anonymous function:
(function ( window, undefined) {
/*
...jquery code...
*/
}) (window);
I get that the function is executed immediately upon the entire script being read, but what is the purpose of the arguments? One is a global object reference, the other is a property reference.
Now, I remember that earlier in the script development, undefined actually got defined as something else (am I remembering that right?). Was that related to this?
Also, it looks like the function is being used as an operator? Just like it is above, I don't understand the syntax of the statement at all. Maybe there is context that would help?
The wrapper does a number of things:
function(window,undefined)
provides the window and undefined variables to the function
the anonymous call })(window); passes the window variable to the script.
If a user overrides the window object, they will easily be able to modify the script to use the correct window variable i.e.:
(function(window,undefined){})(w);
The lack of a second parameter being passed sets the undefined variable to have a value of undefined which prevents a programmer from messing up jQuery by overriding undefined.
When I use the latest (1.0) release of coffee-script, a simple javascript output looks like this (by default):
(function() {
var a;
a = 1;
}).call(this);
What does .call(this) do and what would be the reason to add it?
It's a way to make sure that the compiled CoffeeScript has its own scope for variable names. This has benefits in terms of efficiency and simplicity (you know you the generated JavaScript won't stomp on variables used by other code). You can disable it with the --bare (or -b) option to the CoffeeScript compiler.
The reason for the call(this) is just to ensure that the CoffeeScript has the same this as the scope where it's placed, because functions don't normally inherit their this object from the surrounding context.
It's creating a function and then calling itself with the parent function/objects scope.
.call and .apply are different methods of invoking a function. You basically created a function that does nothing except set a=1 within its own scope.
In javascript you need to realize that every function is a object, and this is what refers to the current object/function. Using .call(this) overrides this from within the function and replaces it with the one from the calling context.