2011-10-02 73 views
1

我在尋找getter和setter的功能,但不能依賴於__defineGetter____defineSetter__。那麼如何在函數調用之間維護函數變量的值?如何在調用之間維護JavaScript函數變量狀態(值)?

我嘗試了很明顯,但MYVAR總是在函數的開始未定義:

FNS.itemCache = function(val) { 
    var myvar; 
    if(!$.isArray(myvar) 
     myvar = []; 
    if(val === undefined) 
     return myvar; 
    .. // Other stuff that copies the array elements from one to another without 
     // recreating the array itself. 
}; 

我隨時可以把另一個FNS._itemCache = []只是上面的函數,但有封裝中的值的方法函數之間的調用?

+1

您是否錯過了右括號 – mowwwalker

+0

是否需要保密? – David

回答

3

的另一種方式設置爲私有變量是由一個匿名函數包裝函數定義的私有成員的標準模式:

(function(){ 
    var myvar; 
    FNS.itemCache = function(val) { 
     if(!$.isArray(myvar)) 
      myvar = []; 
     if(typeof val == "undefined") 
      return myvar; 
     .. // Other stuff that copies the array elements from one to another without 
      // recreating the array itself. 
    }; 
})(); 

這樣,myvar被定義在FNS.itemCache的範圍內。由於匿名函數包裝器,變量不能從其他地方修改。

4

可以通過使用arguments.callee作爲參考,以當前函數存儲關於該函數的值:

FNS.itemCache = function(val) { 
    if(!$.isArray(arguments.callee._val) 
     arguments.callee._val = []; 
    if(val === undefined) 
     return arguments.callee._val; 
    .. // Other stuff that copies the array elements from one to another without 
     // recreating the array itself. 
}; 

然而,如果功能被存儲在一個原型,因此由一個以上的使用,這將破壞目的。在這種情況下,您必須使用成員變量(例如this._val)。

4

這是創建靜態變量,用於創建對象

FNS.itemCache = (function() { 
    var myvar; 
    if(!$.isArray(myvar) 
     myvar = []; 
    return function(val) { 
     if(val === undefined) 
      return myvar; 
     .. // Other stuff that copies the array elements from one to another without 
     // recreating the array itself. 
    } 
})(); 
相關問題