2011-09-02 101 views
2

我覺得這裏有點無知,但我認爲一些教育不會傷害到我。JQuery插件範圍問題

我簡化了我的代碼來概述問題 - 問題是,當從init方法內調用foo()時,它不能訪問假定的全局變量a,b,c和設置。這些是在方法範圍外定義的,爲什麼它們不可訪問?

例如,在foo調用之前明確定義了設置,那麼foo爲什麼看不到設置?

(function(jQuery) { 

a = new Date(); 
var b; 
var c = 1; 
settings = 0; // Here or not - same issue 

var methods = { 
    init : function(settings) { 

     c = $(this);    

     settings = jQuery.extend({ 
       id: Math.floor(Math.random()*1001), 
       x: 3; 
       etc: 2   
      }, settings || {});    

     m = 1; 

     foo();    
    } 
}; 

function foo() 
{ 
    x = settings.x; // settings is not defined 
    var n = c.m; 

    return x; 
} 

jQuery.fn.bar= function(method) { 

    if (methods[method]) // If we have a method that exists 
    { 
     return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); 
    } 
    else if (typeof method === 'object' || ! method) // Otherwise if we get passed an object (settings) or nothing, run the init. 
    { 
     return methods.init.apply(this, arguments); 
    } 
    else 
    { 
     $.error('Method ' + method + ' does not exist'); // Otherwise we have an error. 
    }     

}; 
})(jQuery); 

任何想法?

+0

這並不重要,但你沒有var =賦值,你聲明頁面頂部的設置 – jammypeach

+0

在你的例子中,「settings」沒有定義,或者「settings.x」沒有定義?在foo()中,設置應該等於0,但settings.x應該是未定義的...你能確認嗎? – Timbo

+0

@Timbo - 我確認...設置= 0,settings.x是未定義的。什麼是範圍? –

回答

3

您正在創建的設置的本地副本,當你將它定義爲一個參數傳遞給你的初始化函數:

// Here there is a global settings 
init : function(settings) { 
    // Here there is a local settings 
    // Changes made to it won't affect the global 

所以,當調用函數foo設置仍爲0,並且您正在訪問Number(0).x這是不確定的。

只刪除設置的本地副本將解決你的問題:

init : function(s) { 

,並更改settings || {}s || {}

+0

100% - 我現在看起來很有意義。我沒有注意到我壓倒了它。 –

0

這是因爲初始化功能發生在一個參數設置,這是本地的初始化

如果foo要訪問設置變量init sets,那麼它應該調用foo

foo(settings); 

function foo(settings) 

如果你不想修復你的問題,那麼init應該取另一個參數名稱,然後設置設置值。