How do jQuery plugins maintain global state?

I recently wrote my first simple jQuery plugin. I am proud.

http://jsfiddle.net/johnhoffman/wSeLY/1/

(function($) {
    $.fn.makeRed = function() {
        return this.each(function() {
            $(this).css("color", "#f00");
        });
    }
})(jQuery);

I wonder why this works. I pass the jQuery object to this private function, which runs immediately.

Subsequently, it is not | $ | local variable object inside this anonymous function? How will this change the global single-threaded jQuery object?

In other words, I'm not just adding a function through $.fn.myFunctionNameto the object | $ | locally to a private function? How can I change the global jQuery object and make my function ( makeRed) available to selectors throughout the global area of ​​my script?

+3
source share
2 answers

| $| ?

, $ - , , , jQuery, . :

window.jQuery (global) ----->-----> { ... }
                                    ^
                                    |
$ (local) ------------------>-------+

, , , .

+2

Javascript , jQuery. $.

: Javascript: The Good Parts .

+2

All Articles