I have recently written my first simple jQuery plugin. Proud I am.
http://jsfiddle.net/johnhoffman/wSeLY/1/
(function($) {
$.fn.makeRed = function() {
return this.each(function() {
$(this).css("color", "#f00");
});
}
})(jQuery);
I am wondering why it works though. I pass the jQuery object into this enclosed function that runs immediately.
Subsequently, isn’t the |$| object a local variable within that anonymous function? How does it change the global singleton jQuery object?
In other words, aren’t I just adding a function via $.fn.myFunctionName to the object |$| local to the enclosed function? How does it change the global jQuery object and make my function (makeRed) available to selectors all over the global scope of my script?
Yes,
$is a local variable in the function but, and this is a big but, it is a reference to thejQueryobject that is globally accessible. Things look like this:So, you have two variables that point at the same object and that object still exists after your anonymous function is called.