What does following a function with (jQuery, window, document); mean? [duplicate] - javascript

This question already has answers here:
How does this JavaScript/jQuery syntax work: (function( window, undefined ) { })(window)?
(5 answers)
Closed 4 years ago.
I have the following plugin:
;(function($, window, document)
{
...
...
})(jQuery, window, document);
I can understand what the ; is for and also realize that $ is the jQuery but can someone explain why is the function followed by (jQuery, window, document);

It's called a 'self ivoking' or 'immediately invoked' function. It means that the function is run as soon as it is created using the parameters in the final set of brackets.
Further information

This is called Immediately-Invoked Function Expression or Self-executing anonymous function. It enables the developer to hide his private declarations.
;( // <---------------+
// | encapsulate the function
function($, window, document) { // <--+ declare | and call it passing three
// | anonymous | arguments.
} // <--+ function |
// |
)(jQuery, window, document); // <---------------+

I'm not sure I fully understand what you are asking, but what they do is that they pass the jQuery object, the window object and the document object to the function.
Most likely they do this for performance reasons. This makes it possible for a minimizer to shorten all the references to window and document to something like w and d, since it is local variables. In a large library, that could save a few bytes.
Additionally I believe (have no reference atm) that it is slightly faster to access a local variable, compared to a global variable (really a micro optimization though).

It's an Immediately-Invoked Function Expression
That means, the function is declared and executed right away. This this done in order to create a new scope.

It's an anonymous function that's immediately invoked (the so called IIFE).
The passing of jQuery aliases it to $, and window and document so they can be sure the reference is to the correct version in the outside environment.

Related

Self-invoking function jQuery [duplicate]

This question already has answers here:
What is the purpose of this? (function ($) { //function code here })(jQuery);
(4 answers)
Closed 9 years ago.
I noticed that in some places, jQuery code is wrapped in a self-invoking function like below. Why is this done, in what cases is this useful and in what cases is an unnecessary boilerplate?
function( $ ) {
...
}( jQuery );
The short answer: To prevent variable name conflicts. It is not always needed, but good practice in order to create conflict free reusable code.
The long answer: In javascript the $ symbol is just another variable. jQuery uses it because it is a nice shorthand instead of having to type out jQuery each time, but so can any other code (including other libraries).
To prevent conflict with other uses of a variable at the same scope (in this case $ at the "global" scope) it is common for code to be wrapped in a self-invoking function with the "conflict-free" variables passed as the function parameters. This then creates a new scope where your variable won't interfere with other uses of that variable. That way you can pass the full named variable & uses it with whatever name you want within the anonymous function.
So, when creating conflict free reusable code it is good practice to use this methodology:
(function( $ ) {
...
})( jQuery );
Along these lines you will also see the following format:
(function( $, window, undefined ) {
...
})( jQuery, window );
In this instance undefined is simply used for readability to indicating that no more arguments are passed to the function.
In case you want to avoid conflict regarding use of $
function( $ ) {
...
}( jQuery );
Inside this function you can use $ without having to worry about it's use outside of it as inside that function, $ always refers to the jQuery object.
This is helpful while creating jQuery plugins,You will see jQuery plugin's use this kind of function to avoid conflicts with other plugins.
Reference : http://learn.jquery.com/plugins/basic-plugin-creation/
In function scope $ is local variable that not conflict with any other global $.

What does passing params in a jQuery plugin mean?

I've seen quite a lot of plugins which include objects like document, window, undefined into the arguments of both opening and closing.
Is this necessary?
What does it mean?
When should these be used?
;(function( $ , document, window, undefined) {
"use strict";
$.fn.pluginname= function(options) {
//Code
};
})( jQuery, document, window, undefined);
From jqueryboilerplate.com
// undefined is used here as the undefined global variable in ECMAScript 3 is
// mutable (ie. it can be changed by someone else). undefined isn't really being
// passed in so we can ensure the value of it is truly undefined. In ES5, undefined
// can no longer be modified.
// window and document are passed through as local variable rather than global
// as this (slightly) quickens the resolution process and can be more efficiently
// minified (especially when both are regularly referenced in your plugin).
Fore some extra credit, follow the link and you will see why the method signature is prefaced with a semi-colon.
Also, your example is a bit incorrect: you should not be passing in 'undefined' on the last line when you invoke the function. The reasoning is explained in the first paragraph I pasted in above.

Troubles with (function(){})() [duplicate]

This question already has answers here:
What is the purpose of a self executing function in javascript?
(21 answers)
Closed 8 years ago.
So far I've learned the benefits of using this function (is it wrapping?)
So, it almost acts like namespaces.
Suppose we have:
( function() {
function foo(){
alert(true);
}
foo(); //alerts true
})();
( function() {
function foo(){ //the same title of the function as above
alert("another call of foo");
}
foo(); //alerts, ok.
})();
Also I've noticed it can access public vars, like this:
var __foo__ = 'bar';
( function() {
alert(__foo__); //alerts bar
})();
I have several questions regarding this approach
What I've tried:
Use Bing for tutorials (I' found them, but many of them don't answer my questions)
Play with passing objects into the body
Find the answer here
But, I'm still beating my head against the wall
So the questions are:
I've seen people pass objects as params, but when DOES it make sense?
For example, what does it mean?
( function(window) {
})(document);
I saw smth like this in Jquery UI Lib
( function($) {
//some code of widget goes here
})(Jquery);
This makes inner code visible outside the function, right? (not sure) Why, this is because
we can access the object (say we have "modal" widget), simply by calling it,
like:
$(function(){
$("#some_div").modal(); //here it's object the we got from the function
});
And the second question is: How does it work.
I've seen people pass objects as params, but when DOES it make sense? For example, what does it mean?
( function(window) {
})(document);
The language does not treat parameters to immediately called functions differently than parameters to other functions.
It makes sense to use a parameter whenever you want a local name in your function body for an input. In this case it's a bit confusing since window and document are likely to be confused.
( function($) {
//some code of widget goes here
})(Jquery);
This makes inner code visible outside the function, right? (not sure) Why, this is because we can access the object (say we have "modal" widget), simply by calling it,
No. It does not by itself make any code visible outside the widget. It's just a parameter definition which provides a new&local name for a global variable.
What makes inner code visible outside is attaching it to an external object as in
$.exportedProperty = localVariable;
which is a common convention in jQuery code.
There are mainly 2 purposes of passing in the window and document objects such as seen below
(function(window, document){
// code
}(window, document);
Javascript can access local variables faster than global variables. This pattern in effect makes the names window and document local variables rather than global, thus making your script slightly faster.
Making these names local variables has another benefit: minifiers can rename them. So if you minify the above script, the local version of window might get renamed to a and document might get renamed to b, thus making the minified script smaller. If you were to reference them as globals, these renamings are impossible because that would break your script.
For more info, checkout these awesome videos
http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/
http://paulirish.com/2011/11-more-things-i-learned-from-the-jquery-source/
on your first question, I dont think you seen window and document but something more like:
(function(doc) {
var fubar = doc.getElementById("fubar"); // === document.getElementById("fubar")
})(document);
you have a self-invoking function (or closure) with arguments like any function:
var b = function(str) { alert(str); }
b('hi there') //alert('hi there');
the same thing is it with the code above, but we are just calling the method at once we created it.
the other code you have:
( function($) {
//some code of widget goes here
})(Jquery);
is to reserve the $variable inside the metod to refer to the jQuery object, this is very handy if you have more frameworks or replaced the $ object with something else, everything inside that method with an $ will refer to the jQuery object and nothing else(if you don´t replace it inside your code).
the code:
$(function(){
$("#some_div").modal(); //here it's object the we got from the function
});
is calling jQuery and its a shortcut for $(document).ready
it will call the method:
function(){
$("#some_div").modal(); //here it's object the we got from the function
}
as soon as the DOM is ready
The pattern is called a closure. It makes sense to use when a module or function:
wants to avoid polluting globally-scoped variables
wants to avoid use globally-scoped variables and avoid other code polluting them
For an example of each, first take this pattern:
(function(window) {
// ...
})(window);
Everything inside the closure will be able to use window as if it were a local variable.
Next, take the same pattern using the JQuery symbol:
(function($) {
// ...
})($);
If you have some code that relies on a symbol/namespace like $, but another module reassigns that, it can screw up your code. Using this pattern avoids this by allowing you to inject the symbol into a closure.
Whenever you pass an argument to that wrapping function it's so that you won't mess up with any other libraries or global variables that may be present in your application.
For example as you may know jQuery uses $ as a symbol for calling itself, and you may also have another library, that will also use $ for calling itselt, under this condition you may have trouble referencing your libraries. so you would solve it like this:
(function($){
// here you're accessing jQuery's functions
$('#anything').css('color','red');
})(jQuery);
(function($){
// and in here you would be accessing the other library
$.('#anything').method();
})(otherLibrary);
This is specially useful when you're making jQuery or any other kind of library plugins.
What it does is allow you to use the $ variable inside your function in place of the jQuery variable, even if the $ variable is defined as something else outside your function.
As an example, if you're using both jQuery and Prototype, you can use jQuery.noConflict() to ensure that Prototype's $ is still accessible in the global namespace, but inside your own function you can use $ to refer to jQuery.

Enclosing js function between ()? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Difference between (function(){})(); and function(){}();
I have seen it a lot by google:
(function(){/*code*/})
Why they enclose their function inside the parethesis?
Which is the difference between:
function(){/*code*/}
?
Edit
Ok the questions should have been this:
Why they enclose their code into this:
(function(){/*code*/})();
Instead to write the code directly into the js flow?
Are there any benefits, different behaviour?
I usually use immediate functions to control the variable scope so as not to pollute the global name space. It's a very useful pattern.
(function (window, $, undefined) {
// This pattern gives you the following benefits:
// * all variables defined in here are private
// * can safely minify global variables: window, jQuery & undefined
// * ensures that window, $, undefined mean what you expect
// * global variables are localized so lookups are faster
}(this, jQuery));
So even if someone does window = ‘Bob’ or the shortcut $ doesn’t equal jQuery but instead is the Prototype library, the code inside this immediate function will still work correctly. While you may think to yourself “I’d never set undefined to something else”, keep in mind you’re not the only one putting code into the page; you can’t afford to have a poorly written ad script from DoubleClick bringing down the site, especially when it is so easily prevented.
JavaScript’s global scope is like a public toilet. You can’t always avoid it, but try to limit your contact with surfaces.
what you see is a self executing function:
var x = (function(bar){
return bar;
})('foo')
alert(x);
It's usually done to force the parser to treat it as a function expression and not a declaration.
This is because usually the code looks like this:
(function(){/*code*/})();
The reason for the extra parenthesis is that this is not legal syntax:
function(){/*code*/}();
It's needed for immediate functions as #daniellmb said. See explanation of expression closure for more information.

How do jQuery's namespaces work? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What does this JavaScript/jQuery syntax mean?
I specifically mean when you do this:
(function ($) {
...
})(jQuery);
I've never seen that kind of syntax before. How does the function get called? I understand when you do it like this:
jQuery(function ($) {
...
});
because the function is being passed to jQuery, and jQuery can just run any function passed as a parameter when the DOM's ready, but the first one's different.
Duplicate of What does this JavaScript/jQuery syntax mean?
I'll post my answer here, though seeing as Jeff Attwood seems to want us to embrace duplication: (https://blog.stackoverflow.com/2010/11/dr-strangedupe-or-how-i-learned-to-stop-worrying-and-love-duplication/)
This convention is used when writing plugins to ensure there is no confilict with other Javascript libraries using the $ notation, whilst ensuring the plugin author can still use this notataion:
(function($){
...
})(jQuery);
The author is declaring an anonymous function with a single parameter ($), then immediately calling it and passing the jQuery object to it. This ensures the function is called and that everything in it is defined.
A longer notation might be:
function MyDefs($){
...
}
MyDefs(jQuery);
Although that would create a variable MyDefs in the global namespace. The anonymous function pattern leaves the global namespace empty, avoiding conflicts.
It's an anonymous function. When you write:
(function ($){
..
})(jQuery);
It is mostly equivalent to:
function the_function($) {
..
}
the_function(jQuery);
The only difference being that the first does not create a function called the_function and therefore created no risk of accidentally overwriting an existing function or variable with that name. And of course, all of it is equivalent to:
function the_function() {
var $ = jQuery;
..
}
the_function();
The point of this construct is that any variables defined inside the_function are local and therefore cannot accidentally overwrite any variables or functions in the global scope. For instance, the code inside the function uses $ to represent the jQuery object, but this would conflict with other libraries that use $ as well (such as Prototype). By wrapping the usage of $ inside a function, the Prototype code outside the function remains unaffected.

Categories

Resources