2014-03-30 196 views
4

我會知道我們是否可以在函數中聲明一個靜態變量,就像我們在JavaScript中所做的那樣。在函數中使用靜態變量()

當我回調我的功能,我的變量保持她最後的作風。

或者我可以只使用全局變量(這不是性感......)?

+0

只能使用全局變量。這是Dart語言的限制。爲什麼發生這種情況,你必須詢問Dart語言的設計者。 – mezoni

回答

4

您不能在函數中使用靜態。

Dart中的全局變量沒有代碼異味,因爲它們只是庫全局。
JavaScript中的全局變量很醜,因爲它們可能與第三方庫中的全局變量衝突。
這在飛鏢中不會發生。

正如你可以在達特庫小到你想要的(例如只有一個變量),你有類似的命名空間的庫的東西,當你導入它像

import 'my_globals.dart' as gl; 

和然後像

print(gl.myGlobalValue); 

這是沒有代碼味道。

你也可以創建一個類來模擬一個命名空間像

class MyGlobals { 
    static myVal = 12345; 
} 

但庫全局變量是首選,而不是隻包含靜態變量或函數的類的飛鏢。

1

您只能使用全局變量。

您也可以通過使用「mangling」名稱的私有變量來解決此問題。

void main() { 
    myFunction(); 
    myFunction(); 
    myFunction(); 
} 

int _myFunction$count = 0; 

void myFunction() { 
    print(_myFunction$count++); 
} 

這不會有很大幫助,但你可以考慮用名「_myFunction $伯爵」變量是功能「myFunction的」本地靜態變量「計數」。

與此僞代碼相同。

void myFunction() { 
    static int count = 0; 
    print(count++); 
} 
3

您可以使用函數對象來維護狀態:

library test; 

class Test implements Function { 
    var status = 0; 
    static var static_status = 10; 

    call() { 
    print('Status: $status'); 
    print('Static status: $static_status'); 
    status++; 
    static_status++; 
    } 
} 

void main() { 
    var fun = new Test(); 

    fun(); 
    fun(); 
    fun(); 

    var fun2 = new Test(); 

    fun2(); 
    fun2(); 
    fun2(); 
} 

輸出:

Status: 0 
Static status: 10 
Status: 1 
Static status: 11 
Status: 2 
Static status: 12 
Status: 0 
Static status: 13 
Status: 1 
Static status: 14 
Status: 2 
Static status: 15 
+0

絕對是聰明的點,但我不知道我會推薦它在實踐中通過庫變量或只是將函數放在類上,並在類中使用靜態變量。 –