I've been making a program and I want to know the difference between starting two functions like so:
$(function () {
//content
});
and
function Name () {
//content
}
Also, why can't I name the first example? I tried changing the first example to the second type, and the function stopped working fully. I've used jQuery with the first example and everything was fine, but with a different example, the function stopped working.
So what's the difference?
$(function () {});
this is shortcut for $(document).ready(function(){});
while this:
function Name () {
//content
}
is standard javascript function.
The first is a function expression that is used for the jQuery ready
event, while the second is a function.
Using $(function(){...});
is shorthand for $(document).ready(function(){...});
.
The ready
event happens when the document has completed loading, so the event handler will run automatically. A regular function doesn't run at all unless you call it.
You can naturally use a regular function instead of the function expression for the event handler:
function readyHandler() {
...
}
$(readyHandler); // or $(document).ready(readyHandler);
A function expression can be named, for example:
var x = function y() { ... };
However, the name of the function expression (y
in the example) is not global, it's only usable inside the function itself. Also, the exact implementation of this differs between browsers, so you should avoid using it.
The first one is a so-called anonymous function. It gets executed on the document ready event
$(document).ready(...);
and is jQuery convention. Since you cannot call it directly, it has no / needs no name.
The second version is a standard function that you can call by name at any time.
If you change the first one to the second notation, it will no longer run at document ready automaticly. Safe way is to move the "worklaod" into a function with the second notation, and create a line with the first notation that calls the funciton. That way you have the best of both worlds: a separately callable function, and simple auto-execution.
The first one:
$(function () {
//content
});
is passing an anonymous function to the jQuery object $, equivalent to $(document).ready(function(){});
the second is just a JavaScript function named Name
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With