JQuery Plugin Confusion Tutorial

I need to miss something. The jQuery plugin tutorial was found here in the "Namespacing" section → The "Plug-in Methods" section contains a hidden plugin declaration. What I am not getting here is the scope of the variable methods ; I mean, shouldn't methods be defined as a var tooltip? After the execution of this anonymous function, the methods disappear from scope, if I understand correctly, because it is defined as a var function inside the function. How does this tooltip refer to var methods that will not be available when a tooltip is called? What am I missing?

(function( $ ){ var methods = { init : function( options ) { // THIS }, show : function( ) { // IS }, hide : function( ) { // GOOD }, update : function( content ) { // !!! } }; $.fn.tooltip = function( method ) { // Method calling logic if ( methods[method] ) { return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.tooltip' ); } }; })( jQuery ); 
+4
source share
3 answers

The function assigned by $.fn.tooltip is to close [Wikipedia] and therefore has access to all higher areas.

When an external function returns, methods not destroyed because the closure still refers to it.

+7
source

It does not go out of scope just like your plugin still contains a link to it. In JS, they are called closures .

+1
source

All this works due to closure. The function pointed to by $.fn.tooltip is actually a closure. Thus, he has access to the method object.

0
source

All Articles