jQuery question: what does it really mean? - javascript

(function($, window, undefined){
... jquery code...
})(jQuery, window);
What does it really mean? Does it also mean $(document).ready()? Or just two different things?

There are already two answers but this is my guess on the missing end of the code:
(function ($, window, undefined) {
// ... jquery code...
})(jQuery, window);
Note: three parameters are expected but two are supplied.
What it basically does is:
gives a private scope inside curly braces, so any var declared inside is not visible outside
makes a private $ shortcut to jQuery without relying on this shortcut being set globally (eg. jQuery.noconflict() might have been called and this would still work)
makes a lexical window variable that would mean faster lookups for global variables
makes sure that undefined is indeed undefined in the scope between curly braces, even if someone has written something like undefined = "now it's defined"; in the global scope, because undefined can actually be redefined (this is a mistake of the language).
This pattern is known as immediately invoked function, or immediate function for short, or self-invoking anonymous function, or some other names. The basic idea is that:
(function (x, y) {
// ...
})(1, 2);
or:
(function (x, y) {
// ...
}(1, 2));
means the same as:
function myFunction (x, y) {
// ...
}
myFunction(1, 2);
but without the need to give any name to your function and pollute the namespace.
Going back to your question, this doesn't mean $(document).ready() or anything like that, but it means that you can use $(document).ready() inside instead of jQuery(document).ready() even if the $ shortcut is not available outside.
This example may actually explain it better, even if it isn't used anywhere:
(function (JQ, window, undefined) {
JQ(document).ready(function () {
// this is run when document is ready
});
})(jQuery, window);
Now instead of $ you can call jQuery as JQ and use JQ(document).ready() instead of $(document).ready() – it may not seem very useful but it shows what happens when you have a code like that.
As a side note I might add that thanks to this pattern you don't actually need variable declarations in the language but only function arguments. Instead of:
var x = 10;
alert(x * x * x);
you could use:
(function (x) {
alert(x * x * x);
})(10);
and indeed a function like this:
function square (x) {
// some code ...
var result = x * x;
return result;
}
is exactly equivalent to:
function square (x, result) {
// some code ...
result = x * x;
return result;
}
because of the hoisting mechanism in JavaScript that would make the result variable available (but undefined) even before the declaration and assignment in both cases (in the // some code ... part). This is often a source of confusion but is actually quite interesting and extremely powerful.
See also my other recently updated answer to the question:
Help understanding JavaScript global abatement techniques for more info on this subject.

(function($, window, undefined){
... jquery code...
})();
is different than
$(document).ready()
Paul Irish has a good video on 10 Things I Learned from the jQuery Source at 1:30 in he talks about the jquery source's self executing anonymous function and what the arguments mean

Like that it doesn't mean much at all (in addition a closing ) is missing). What you are probably looking at is something similar to this:
(function($, window){
// code
} )($, window);
This puts the code inside a new scope, so you can for example define variables without messing with the outside scope.
It also allows that you pass different things to the function, without having to change the code. For example if you use different JavaScript frameworks, and $ is not bound to jQuery, you can pass the alternative variable for jQuery instead, while you are still using the $ to refer to jQuery internally. Similar to that you could also pass a different window instance (for example from a popup).

I'm guessing the code actually looks like this:
(function($, window, undefined){
... jquery code...
})(jQuery, window);
Note the parenthesis at the end.
If this is the case, what's going on here is a self-executing anonymous function. The point of doing this is that any local variables or functions defined inside of that anonymous function will not pollute the global namespace.

#rsp has a great answer for this specific question.
For general background on this pattern also see http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth.

Related

why are javascript functions like this [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does this mean? (function (x,y)){…}){a,b); in JavaScript
I am a starter to javascript. I know to write JS userdefined functions.
But recently I came across some thing that I can’t recognize. Can anyone explain to me what this is?
(function( window, undefined ) {
var jQuery = (function() {
});
window.jQuery = window.$ = jQuery;
})(window);
What is the meaning of this? When I Google javascript functions I am getting only
function foo(){
alert("This is an alert");
}
I know to use these type of functions
Short answer: Those are immediately invoked functions that provide lexical scope and closures.
For a better explanation please take a look at this answer I posted some time ago.
UPDATE:
Lexical scope means that variables declared within a function won't be visible outside of the function body.
Closure is a way to keep references to variables that would otherwise be out of scope, because if they were in scope where the function body was defined then it is available to any subsequent invocation of that function. See: Closure on Wikipedia.
UPDATE 2:
If you really want to understand all of these then I strongly recommend watching the 1986 Structure and Interpretation of Computer Programs MIT lectures by Gerry Sussman and Hal Abelson
(available on YouTube). In my opinion there is no better way to truly understand JavaScript than watching those very lectures, even though they are not about JavaScript. You will quickly see which language was really the inspiration for Brendan Eich when he designed JavaScript. Hint: It was not Java.
It is a Function that executes itself, also called a module pattern.
It is often used to introduce public and private namespaces since attributes defined on the inside of said function are not accessible from the outside while attributes you return are.
For example, if you return an object, you can then treat the function as an object like this:
var a = (function() {
var a= 0; // this is only accessible inside this function
var b = {
a: 1 // this will be returned and therefore be accessible on the outside
};
return b;
})();
console.log(a.a); // outputs 1
The following is a function statement. It can exist alone.
function foo(){
alert("This is an alert");
}
It can be 'called' (executed) like this:
foo();
The following is a function expression (such as anonymous function ** see edit at the bottom **).
As any other expression, it is like an rvalue, you can assign it to a variable
var f = function (){
alert("This is an alert");
};
which, then, can be 'called' (executed) like this:
f();
or you can use operators over it like this:
(function (){
alert("This is an alert");
})();
And note that this variable can now be passed as parameter to other functions! (i.e. we can pass functions as parameters).
Now, lets analyze this:
(function( window, undefined ) {
//blah blah blah -1
//blah blah blah -2
})(window);
this can be broken down into two:
var f = function( window, undefined ) {
//blah blah blah
};
f(window);
The function (assigned to f) takes 2 parameters, window and undefined. We are passing the 1st parameter as window (which will be provided by the browser to the caller; it's a global object). Note that we are not passing any 2nd parameter. But since we are expecting 2nd param in the function but not passing any, the Javascript interpreter will assign an undefined value (as defined in the interpreter) to it. So the variable (parameter) undefined now contains undefined.
The main purpose of accepting these two values as parameters is to make the function independent of the global variables. (Just imagine what would happen if some JS script or a browser plugin changes undefined to something else!!)
Refer:
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Functions
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Expressions_and_Operators
EDIT:
As #FelixKling commented, function expressions need not be anonymous, they can have names.
var f = function foo(){
alert("This is an alert");
}
This is an interesting article about their usage.

JavaScript piece of code explanation

Check out this piece of JavaScript code:
(function (w, d) {
var loader = function () {
var s = d.createElement("script"), tag = d.getElementsByTagName("script")[0];
s.src = "https://example.org/script.js";
tag.parentNode.insertBefore(s,tag);
};
w.addEventListener ? w.addEventListener("load", loader, false) :
w.attachEvent("onload", loader);
}) (window, document);
Why did the author of this code use this method to include a script in the document?
And what is the usefulness of the line:
w.addEventListener ? w.addEventListener("load", loader, false) :
w.attachEvent("onload", loader);
Last point: I'm a JavaScript beginner, what is the (window, document) at the end?
The first question, the code checks to see if window.addEventListener is defined. If it is, it uses it, otherwise it uses window.attachEvent. This is for browser compatibility.
The 2nd question, this code is an anonymous function which takes 2 parameters, w and d. This function is immediately called, passing the parameters window and document.
The following addEventListener line is to register the function so that it gets called when the page finishes loading. Internet Explorer and Firefox (et al) use different functions to do this.
w.addEventListener ? w.addEventListener("load", loader, false) :
w.attachEvent("onload", loader);
In javascript a function is an object in and of itself. As such it's 'value' can be assigned to a variable or consumed immediately. To consume it immediately it must be wrapped in parentheses (otherwise it won't do what you want) and then call it like it were a regular function.
(function (w, d) { ... }) (window, document);
It's more obvious what is going on if we break it up across two lines.
var a = function(w, d){ ... };
a(window, document);
It was done this way to as to not pollute the global scope with temporary values or functions. Not to mention not trashing anyone else variables. This can be broken into two parts:
By encapsulating the code in a closure anything explicitly declared inside is in the closure's scope, not the global scope. var loader is in the closure's scope.
By consuming the closure immediately it won't be stored in a variable in the global scope. Since it was declared anonymously it won't exist as a named function in the global scope.
Firstly, w.addEventListener ?to make sure if the browser supported the addEventListener method of window
Secondly, (window, document) is just parameter call of anonymous function he wrote before function(w,d) {}
It looks like the author is waiting for the page to be fully loaded before attaching the script tag. addEventListener (DOM level 2) and attachEvent (Microsoft stuff) are more flexible ways of attaching events. The code is similar to saying w.onload = loader.
The last bit is passing arguments into the anonymous function, where they are named w and d. By putting the () at the end, the anonymous function is invoked right away.
So the function is wrapped in a closure. Which in turn means w = window and d = document.
When the method is called the it creates a function called loader which is the callback for one of the two possible event listener triggers (meaning, that'll be called when the load or onload event is called on the window).
The x ? y : z syntax is a shorthand if then else call.
If we expanded that out, it'd look like this:
if (w.addEventListener) {
w.addEventListener("load", loader, false);
} else {
w.attachEvent("onload", loader);
}
that statement is used cater the method for both IE and other browsers.
The author of this code is using an anonymous function wrapped in a closure to fire off the function, which registers a load event. The script on the page will not actually be loaded until the window's onload event fires.
The reason that the author may be delaying the script load may be to give the web page more time to render before actually loading in the other script. This is a great technique to load page content quickly while delaying the loading of resources that are not immediately needed.
The technique the author is using is an anonymous function wrapped in a closure. Picture this:
myFunction (window, document);
Now, I'm going to replace the function call with an anonymous function:
function(w, d) {
// do stuff
alert("w = " + w);
alert("d = " + d);
}
Now I'm going to cause that function to run immediately, without actually giving it a name. I'm also going to pass two parameters into that anonymous function:
( function(w, d) {
// do stuff
alert("w = " + w);
alert("d = " + d);
}) ("1234", "5678");
The output in this example would be:
w = 1234
d = 5678
If you watch the parentheses and match them up, the first outer parentheses matches the closing parentheses on the last line at character 2, that is the function name, and the following set of parentheses wrap the two values passed into the function as parameters.
This can be a tough concept to grasp at first; after you see it done a few times, it starts to make more sense.
Adding the script that way allows the author to include that script in the document without directly editing HTML files. Can also be used to dynamically load a script only when needed. (i.e. if you have a bunch of code to edit something on the page, you don't want to download it until the user actually clicks the edit button, so you don't waste bandwidth when it's not needed).
addEventListener and attachEvent are ways to trigger a function to be called when the page has finished loading. In this case, there's a function named loader
The reason for both is that some browsers support one and some support the other. I've been using jQuery long enough that I don't remember which is which.
(window, document) is a way to encapsulate those variables in scope and/or refer to them by shorthand w and d. The author is creating a function that expects those parameters, then passing both window and document as the arguments for them.
The closure also helps the author keep from having his script clash with other scripts on the page. Think of every variable declared in there like it's a private variable in other languages.
This is effectively the same as:
function RegisterEventListener(w, d) {
var loader = function () {
var s = d.createElement("script"), tag = d.getElementsByTagName("script")[0];
s.src = "https://example.org/script.js";
tag.parentNode.insertBefore(s,tag);
};
if (w.addEventListener) {
w.addEventListener("load", loader, false);
} else {
w.attachEvent("onload", loader);
}
}
RegisterEventListener(window, document);
The only real differences are:
If you define an anonymous function (using function () {};) without assigning it to anything it is only available for limited use (because there is no way to reference it). At the same time, anonymous functions also allow immediate execution (like the one in the code from your question function(a, b) {}(a, b);.
The condition ? true : false (tertiary operator) is just shorthand for writing simple if statements so it requires less typing to write out, but some people also see it as being less readable.
The window, document at the end of the first block of code are arguments to the anonymous function defined in the rest of the code block. Since Javascript is pretty much a functional language programmers are allowed to define these anonymous functions and even use them without giving them a name.
The block of code you pasted with the question mark is an example of infix notation, a language construct that fits this pattern: condition ? ifTrueExpression : ifFalseExpression. Where condition is true, the entire expression will be equal to ifTrueExpression. Otherwise, the entire expression will be equal to ifFalseExpression.
The use of infix notation you pasted is common in detecting which type of internet browser is being used. Although, I'm not sure which browser this block of code is trying to detect, its intent is to implement an event handler in a browser specific way.
I may be wrong, but this is the implementation used by Google with their analytics script.
This is called a closure, a function that is autoexecuted and enclose the variables inside, so they can't mess with your code.
This codes essentially creates a script tag and append this to the DOM before the first script tag it finds in the document.
The answer for the first question is about browser compatibility. some browsers use addEventListener and others attachEvent to attach events to elements in the page (in this case, the window) and it will lounch on the load event of the window (when all content is loaded, after the document is ready). Take a look at this for a more detailed answer: window.onload vs $(document).ready()
The second answer is simple. This are the parameters used in the closure (the auto calling function) and can be read in this way:
function anonymous(w, d) {
...
}
anonymous(window, document);

purpose of "(function() {" at the start of scripts (GreaseMonkey only?)

I'm pretty new to JavaScript, which I am learning on my own. I'm currently creating and tweaking GreaseMonkey scripts. I've noticed that most simple scripts (i.e. those with no need for named functions) go straight into the main code, but some instead are set up like this:
(function() {
//main code here
})();
What is the significance of this type of coding? I've commented out both the top and bottom, and the script still runs exactly the same.
Is it just a coding standard, or does it actually have a function? And, as my title asks, is it something specific to GreaseMonkey, or something that I should do all the time?
This technique effectively creates a private namespace, accessible only to this script. For example, this code:
(function() {
var a = 5;
})();
will have no effect on the global namespace (the a variable is captured by the closure, so window.a will not be affected). It's a very nice way to keep many scripts from stepping on each other's global variables, by making them not global at all. I use this technique all the time when writing any JavaScript, not just Greasemonkey scripts, and would strongly recommend it as a best practice when writing libraries.
If you wanted to expose some functions to other JavaScript code instead of completely isolating your script, you could do something like this:
var MyNamespace = (function () {
var that = {};
that.square = function(x) {
return x*x;
};
return that;
})();
Then you could do MyNamespace.square(5) from another script, and this would return 25.
It's a self executing anonymous function.
It's usually used to change the scope, all variables/functions declared inside this will be in the anonymous function's scope instead of the global (window) scope.
The code serves two purposes:
It keeps objects/variables local to the anonymous function scope. This is important as we see that you may have several script files that all might share the same variable name. If they did, they could replace the variables value and truly muck with your application.
The () at the the end of the line calls the declared function. In other words, the anonymous function you created inside the first set of parentheses can automatically be called instantly. Unless you assigned it to a variable, there would be no other way to call it. This avoids creating a variable in memory and just calls the function at runtime.
Here's the answer for those who never heard of the word closures:
Suppose we have a function
function sayHi() { alert('Hello'); }
We would call this function by doing this:
sayHi();
The above is whats called a named function, if you don't know what that means, then it's what you think of when you hear the word function
In some languages you don't have to name a function, you can leave it blank like so:
alert('Sup');
function() {alert('Hello'); }
3 + 1;
alert('Peace');
Line 2 is perfectly valid. Of course line 2 won't really do anything in your page, just like line 3 doesn't do anything. That is called an anonymous function. Now just like we can assign a variable to line 3 like:
result = 3 + 1;
We can do the same with line 2, like this:
myFunc = function() { alert('Hello'); };
And we can use myFunc as a function like the sayHi() function before. We call it just like we call sayHi()
sayHi();
myFunc();
Now since javascript is written to be versatile, where stuff like [0, 1, 2].indexOf(1) works, we can do the following:
func = function() { alert('hello'); };
func();
(function() { alert('hello'); })();
And line 1 & 2 will accomplish the same thing as line 3 since line 3 is just an expanded version of line 1 and 2. The advantage of line 3 is that if someone later on in the code uses a func variable it wouldn't cause a problem with your own code, also any variables declared in line 3's function (with a var keyword) won't be a valid variable outside of your function, which in this case is what a closure is.
Well that's it for this micro-tutorial, hope it helps.

how to Custom build a javascript API based on Jquery and some questions about the syntax used in Jquery

I come here with quite a bunch of questions so lets start:
I want to know some things about the syntax used to make jquery as I wish to learn from it an use it for my self.
Question 1:
The starting of the jQuery library
(function( window, undefined ) {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery, .......
I would like to know what is meant by the bracket before the function like so "(function(window..." until now I have only declared my function like this
function myFunc(myArg1,myArg2){
//stuff
}
Question 2:
At the end of the jquery library I seem to understand that the $ sign is assigned in the global scope so that we can use the $ anywhere for the selectors, what i dont understand is that what does the "(window);" expression at the very end mean, and what purpose does it serve.
};
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
})(window);
My final question is, how can I go about making a globally accessable javascript Object of my own that I can use with lets say "ds.functionName(Arg1);" just like JQuery is used with the $ sign
Thank you :D
Question 1 and Question 2 are actually related. What they're doing is defining a function with the (function(params){...}) bit, and executing it straight away with the (window) bit, passing in window as the parameter. It looks quite odd, but it's a neat way of making sure you don't end up polluting the global namespace. If you define your function as function foo(){...}, it means that foo is a function in the global namespace (the window) anybody and everybody can call your function. Even worse, it means that nobody else can define a function foo in global without it trampling all over your function foo. Bad Things happen when this happens :-) 188663 has more info about this pattern.
Third question, jQuery does it nicely. What they're doing with the
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
means that you can call on jQuery or $, and it "just exists", it's way out there in the global scope. You're probably after the module or singleton pattern - 1479319 has some jolly good answers in this regard
1) This creates a closure, so that everything inside is local to this closure, only what the authors intend it exposed and in the global namespace.
2) The window expression is passing a a reference to the window object into that closure, it's the first parameter of function( window, undefined ) { up top, this causes it to immediately be invoked as well.
What you are looking at is called an Anonymous Function. Anonymous Functions can be passed around just like normal variables. They are also executed immediately once they are declared. It's quite a paradigm shift in understanding this concept. I'm sure there are some other explanations here on Stackoverflow that can explain them.
(...your code...)(argument);
So in your second example:
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
})(window);
the argument window is being passed into the anonymous function that started in example 1

JavaScript: Why the anonymous function wrapper? [duplicate]

(function() {})() and its jQuery-specific cousin (function($) {})(jQuery) pop up all the time in Javascript code.
How do these constructs work, and what problems do they solve?
Examples appreciated
With the increasing popularity of JavaScript frameworks, the $ sign was used in many different occasions. So, to alleviate possible clashes, you can use those constructs:
(function ($){
// Your code using $ here.
})(jQuery);
Specifically, that's an anonymous function declaration which gets executed immediately passing the main jQuery object as parameter. Inside that function, you can use $ to refer to that object, without worrying about other frameworks being in scope as well.
This is a technique used to limit variable scope; it's the only way to prevent variables from polluting the global namespace.
var bar = 1; // bar is now part of the global namespace
alert(bar);
(function () {
var foo = 1; // foo has function scope
alert(foo);
// code to be executed goes here
})();
1) It defines an anonymous function and executes it straight away.
2) It's usually done so as not to pollute the global namespace with unwanted code.
3) You need to expose some methods from it, anything declared inside will be "private", for example:
MyLib = (function(){
// other private stuff here
return {
init: function(){
}
};
})();
Or, alternatively:
MyLib = {};
(function({
MyLib.foo = function(){
}
}));
The point is, there are many ways you can use it, but the result stays the same.
It's just an anonymous function that is called immediately. You could first create the function and then call it, and you get the same effect:
(function(){ ... })();
works as:
temp = function(){ ... };
temp();
You can also do the same with a named function:
function temp() { ... }
temp();
The code that you call jQuery-specific is only that in the sense that you use the jQuery object in it. It's just an anonymous function with a parameter, that is called immediately.
You can do the same thing in two steps, and you can do it with any parameters you like:
temp = function(answer){ ... };
temp(42);
The problem that this solves is that it creates a closuse for the code in the function. You can declare variables in it without polluting the global namespace, thus reducing the risk of conflicts when using one script along with another.
In the specific case for jQuery you use it in compatibility mode where it doesn't declare the name $ as an alias for jQuery. By sending in the jQuery object into the closure and naming the parameter $ you can still use the same syntax as without compatibility mode.
It explains here that your first construct provides scope for variables.
Variables are scoped at the function level in javascript. This is different to what you might be used to in a language like C# or Java where the variables are scoped to the block. What this means is if you declare a variable inside a loop or an if statement, it will be available to the entire function.
If you ever find yourself needing to explicitly scope a variable inside a function you can use an anonymous function to do this. You can actually create an anonymous function and then execute it straight away and all the variables inside will be scoped to the anonymous function:
(function() {
var myProperty = "hello world";
alert(myProperty);
})();
alert(typeof(myProperty)); // undefined
Another reason to do this is to remove any confusion over which framework's $ operator you are using. To force jQuery, for instance, you can do:
;(function($){
... your jQuery code here...
})(jQuery);
By passing in the $ operator as a parameter and invoking it on jQuery, the $ operator within the function is locked to jQuery even if you have other frameworks loaded.
Another use for this construct is to "capture" the values of local variables that will be used in a closure. For example:
for (var i = 0; i < 3; i++) {
$("#button"+i).click(function() {
alert(i);
});
}
The above code will make all three buttons pop up "3". On the other hand:
for (var i = 0; i < 3; i++) {
(function(i) {
$("#button"+i).click(function() {
alert(i);
});
})(i);
}
This will make the three buttons pop up "0", "1", and "2" as expected.
The reason for this is that a closure keeps a reference to its enclosing stack frame, which holds the current values of its variables. If those variables change before the closure executes, then the closure will see only the latest values, not the values as they were at the time the closure was created. By wrapping the closure creation inside another function as in the second example above, the current value of the variable i is saved in the stack frame of the anonymous function.
This is considered a closure. It means the code contained will run within its own lexical scope. This means you can define new variables and functions and they won't collide with the namespace used in code outside of the closure.
var i = 0;
alert("The magic number is " + i);
(function() {
var i = 99;
alert("The magic number inside the closure is " + i);
})();
alert("The magic number is still " + i);
This will generate three popups, demonstrating that the i in the closure does not alter the pre-existing variable of the same name:
The magic number is 0
The magic number inside the closure is 99
The magic number is still 0
They are often used in jQuery plugins. As explained in the jQuery Plugins Authoring Guide all variables declared inside { } are private and are not visible to the outside which allows for better encapsulation.
As others have said, they both define anonymous functions that are invoked immediately. I generally wrap my JavaScript class declarations in this structure in order to create a static private scope for the class. I can then place constant data, static methods, event handlers, or anything else in that scope and it will only be visible to instances of the class:
// Declare a namespace object.
window.MyLibrary = {};
// Wrap class declaration to create a private static scope.
(function() {
var incrementingID = 0;
function somePrivateStaticMethod() {
// ...
}
// Declare the MyObject class under the MyLibrary namespace.
MyLibrary.MyObject = function() {
this.id = incrementingID++;
};
// ...MyObject's prototype declaration goes here, etc...
MyLibrary.MyObject.prototype = {
memberMethod: function() {
// Do some stuff
// Maybe call a static private method!
somePrivateStaticMethod();
}
};
})();
In this example, the MyObject class is assigned to the MyLibrary namespace, so it is accessible. incrementingID and somePrivateStaticMethod() are not directly accessible outside of the anonymous function scope.
That is basically to namespace your JavaScript code.
For example, you can place any variables or functions within there, and from the outside, they don't exist in that scope. So when you encapsulate everything in there, you don't have to worry about clashes.
The () at the end means to self invoke. You can also add an argument there that will become the argument of your anonymous function. I do this with jQuery often, and you can see why...
(function($) {
// Now I can use $, but it won't affect any other library like Prototype
})(jQuery);
Evan Trimboli covers the rest in his answer.
It's a self-invoking function. Kind of like shorthand for writing
function DoSomeStuff($)
{
}
DoSomeStuff(jQuery);
What the above code is doing is creating an anonymous function on line 1, and then calling it on line 3 with 0 arguments. This effectively encapsulates all functions and variables defined within that library, because all of the functions will be accessible only inside that anonymous function.
This is good practice, and the reasoning behind it is to avoid polluting the global namespace with variables and functions, which could be clobbered by other pieces of Javascript throughout the site.
To clarify how the function is called, consider the simple example:
If you have this single line of Javascript included, it will invoke automatically without explicitly calling it:
alert('hello');
So, take that idea, and apply it to this example:
(function() {
alert('hello')
//anything I define in here is scoped to this function only
}) (); //here, the anonymous function is invoked
The end result is similar, because the anonymous function is invoked just like the previous example.
Because the good code answers are already taken :) I'll throw in a suggestion to watch some John Resig videos video 1 , video 2 (inventor of jQuery & master at JavaScript).
Some really good insights and answers provided in the videos.
That is what I happened to be doing at the moment when I saw your question.
function(){ // some code here }
is the way to define an anonymous function in javascript. They can give you the ability to execute a function in the context of another function (where you might not have that ability otherwise).

Categories