Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Plugin Tutorial Confusion

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 );
like image 697
gangelo Avatar asked Feb 24 '23 07:02

gangelo


2 Answers

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.

like image 132
Felix Kling Avatar answered Mar 06 '23 09:03

Felix Kling


It doesn't go out of scope exactly as your plugin still holds a reference to it. In JS, they are called closures.

like image 26
Mrchief Avatar answered Mar 06 '23 09:03

Mrchief