I have to be missing something. The jQuery plugin tutorial found here, in the "Namespacing" -> "Plugin Methods" section, there lurks the below plugin declaration. What I am not getting here is the scope of the methods variable; I mean, shouldn't methods be defined as a var in tooltip? Once this anonymous function executes, methods goes out of scope if I understand correctly because it is defined as a var within a function. How is it that tooltip references var methods which will be out of scope when 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 );
The function assigned to $.fn.tooltip
is a closure [Wikipedia] and therefore has access to all higher scopes.
When the outer function returns, methods
is not destroyed because the closure still references it.
It doesn't go out of scope exactly as your plugin still holds a reference to it. In JS, they are called closures.
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