Reputation: 3172
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 );
Upvotes: 3
Views: 355
Reputation: 69905
This all works because of closure. The function which $.fn.tooltip
points to is actually a closure. So it has access to method
object.
Upvotes: 0
Reputation: 76208
It doesn't go out of scope exactly as your plugin still holds a reference to it. In JS, they are called closures.
Upvotes: 1
Reputation: 816324
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.
Upvotes: 7