开发者

jQuery Plugin Tutorial Confusion

开发者 https://www.devze.com 2023-03-27 12:57 出处:网络
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 th

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 sc开发者_JAVA百科ope 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.


This all works because of closure. The function which $.fn.tooltip points to is actually a closure. So it has access to method object.

0

精彩评论

暂无评论...
验证码 换一张
取 消