2012-09-04 30 views
1

我在寫一個jQuery插件,並且經常被某些函數的範圍所困惑(就像使用jS時的傳統一樣)。Structring jQuery插件

簡單例子應該有所幫助:

(function ($) { 

    var methods = { 

     init: function (options) { 
      var settings = $.extend ({ 
       a: 100, 
       b: 200 
      }, options); 

      return this.each(function(){ 

       var $this = $(this); 
       var return_value = $this.plugintest("method_1", settings); 
       $this.plugintest("method_2", settings, return_value); 
      }); 
     }, 

     method_1 : function (settings) { 

      var method_1_value_1 = settings.a * 10, 
       method_1_value_2 = settings.a * 20; 

      return method_1_value_1; 
     }, 

     method_2 : function (settings, old_return_value) { 

      // WHAT IF I WANT BOTH method_1_value_1 AND method_1_value_2 in here? 
     } 
    }; 

    $.fn.plugintest = function (method) { 

     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 in jQuery.robottest'); 
     } 
    }; 
}) (jQuery); 

見method_2。我想訪問我在method_1中創建的值,但是我只能返回1個值 - 我應該創建某種全局變量嗎?做這個的最好方式是什麼?

+0

你可以從你'method_1'與每個值屬性返回的對象。 –

回答

1

變量在聲明它們的函數中可見(即它們的var語句出現的函數)以及在該函數中聲明的任何函數中。

下面是一個例子:

(function() { 
    var foo; 

    // foo is visible here, bar is not 
    // declare variables that should be visible to your whole plugin here 

    var methods = { 
     a: function() { 
      var bar; 
      // foo and bar are both visible here 
     }, 

     b: function() { 
      // foo is visible here, bar is not 
     } 
    }; 
}()); 

// neither foo nor bar are visible here 

你永遠不應該使用全局變量(即不與函數內部var語句聲明即變量)。這些對您文檔中的所有其他代碼都是可見的。但是,只要您將所有內容都包含在function中,並且始終使用var即可。

+0

這是一件好事嗎?我試着這樣做,並被告知這是不好的做法。 – Alex

+1

這是唯一的出路。 – Daniel

+0

好吧,非常感謝。期待一個複雜的解決方法,但這非常簡單! – Alex

0

函數中定義的變量將在函數範圍內。先前在函數之前聲明的任何東西都將在父範圍內。根據您的變量聲明,父範圍將顯示在您的父級範圍內。

所以,如果你在你的父類中聲明你的變量,並且不在你的內部函數中再次聲明它們,將導致從你的內部函數訪問這兩個變量。