I understand how to define functions like this:
function myfunc(x,y,z) {
alert("Just an example " + x + y + z)
}
But not this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
(function ($) {
$.fn.idle = function (x, y, z) {
alert("Just an example " + x + y + z)
}(jQuery));
</script>
The above is a part of a library I'm using, but I simply can't understand the $.fn.idle
bit.
What is it doing? It's defining a function called 'idle', somehow, but what about the $.fn
? And what about the (function ($) {
part? Again, I understand $(document).ready(function() {
but (function ($) {
is completely alien. Is it a short hand?
And what is the significance of the (jQuery));
at the bottom?
An immediately invoked function expression which aliases jQuery
to $
inside its scope:
(function($) {}(jQuery));
It creates and executes a function immediately. This way you can use $
inside the function to reference jQuery regardless of what the global $
references to. Useful for pages using jQuery.noConflict()
. Also the variables declared inside that IIFE don't leak to the global scope.
As for the other part of the question, $.fn === jQuery.prototype
. So by adding a method to the jQuery prototype, you may call it on any jQuery object. E.g.:
$.fn.doSomething = function(){}; //add a method to the jQuery prototype
$('selector').doSomething(); //then you may call it on any jQuery object
More on jQuery plugin authoring.
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