What is the difference between the following function definitions?
1:
$(function () {
//stuff here
});
2:
function($){
//stuff here
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In #1, your function will be called by jQuery when the DOM is ready; passing a function into
$()is a shortcut for$(document).ready(function() { ... });(details here).In #2, you’re defining a function but neither calling it nor asking jQuery to call it. (And in fact, as shown, it’s a syntax error — you’d need to be assigning it to something or calling it for it to be valid without a name.) Nothing you’ve quoted will execute the function, you’d have to call it yourself.
On #2, the idiom you’ve probably seen there is:
That’s fairly standard thing you’d do when you want the code to run immediately (not wait for DOM ready), and you want to use
$within the function to refer to jQuery, but you want to be compatible withnoConflictmode. You see this a lot in plug-ins. It defines a function accepting a$argument, which shadows any$defined globally, and then immediately calls that function passing injQueryas the argument. So even if$doesn’t map tojQueryglobally, it does within that function. You can do the same thing like this:…but for some reason the earlier example is more common, even if a bit less clear. (It’s a couple of characters shorter, I suppose.)