jQuery插件教程混乱

gan*_*elo 4 jquery jquery-plugins

我不得不遗漏一些东西.该jQuery插件教程找到这里,在"命名空间" - >"插件方法"部分,有潜藏着低于插件声明.什么我没有得到这里的范围方法变量; 我的意思是,不应该将方法定义为工具提示中的var吗?一旦这个匿名函数执行,如果我理解正确,方法就会超出范围,因为它被定义为函数中的var.当工具提示被调用时,工具提示如何引用将超出范围的var方法?我错过了什么?

(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 );
Run Code Online (Sandbox Code Playgroud)

Fel*_*ing 7

分配给的函数$.fn.tooltip是一个闭包 [Wikipedia],因此可以访问所有更高的范围.

当外部函数返回时,methods不会销毁,因为闭包仍然引用它.