2014-05-07 56 views
0

這裏就是我想要做的事:如何在函數中爲成員賦值一個變量?

interface FunctionWithState { 
    (): void; 
    state: number; 
} 

var inc: FunctionWithState = { 
    state: 0, 
    apply:() => this.state++; // wrong syntax 
}; 

基本上,我想要的功能,以保持一定的狀態,從外部訪問。我如何分配類型FunctionWithState的變量?

回答

1

對於該特定行,您有一個錯誤的分號。修復:

interface FunctionWithState { 
    state: number; 
} 

var inc: FunctionWithState = { 
    state: 0, 
    apply:() => this.state++ // right syntax 
}; 

但是我懷疑你使用的是()=>錯。您希望它指的是inc,而不是全局變量this,在這種情況下爲window

也許你的意思是使用一類:

interface FunctionWithState { 
    state: number; 
} 

class Inc implements FunctionWithState { 
    state = 0; 

    apply =() => this.state++; 
}; 

var inc = new Inc(); 
inc.apply(); 

如果你真的想成爲它平原javascripty,你可以做到以下幾點。但你不能調用應用功能(因爲它不存在FunctionWithState):

interface FunctionWithState { 
    (): void; 
    state: number; 
} 

var tmp: any = function() { } 
tmp.state = 0; 
tmp.apply = function() { return this.state++; }; 
var inc: FunctionWithState = tmp; 
+0

OK,但我想用'INC'像這樣的功能:'INC()'。我可以這樣做嗎? –

+0

@ Jean-PhilippePellet請參閱更新 – basarat

+0

您是否說我沒有辦法將對象分配給我的問題中定義的'FunctionWithState'類型的變量? –

相關問題