[英]Javascript ES6(ES2015)/ Typescript: how to access local method inside static method
我基本上想訪問靜態“ bar”方法內的“ foo2”方法,但到目前為止,我只能訪問“ foo1”和“ foo3”方法。 誰能教我如何訪問非靜態foo2方法。
let foo1 = () => {
alert('foo1’);
};
class ABC extends Component {
static bar() {
foo1(); //can work
foo2; //not work with error "Can't find variable foo2"
foo2(); //not work with error "Can't find variable foo2"
this.foo2(); //not work with error "this.foo2 is not a function"
this.foo2; //no error but no alert, basically nothing happen
ABC.foo3() //can work
}
foo2 = () => {
alert('foo2');
};
static foo3 = () => {
alert('foo3');
};
}
module.exports = ABC;
警告:不需要從靜態方法訪問實例方法,這可能會使其他開發人員感到困惑。 盡量避免使用它。 如果您確實使用它-請確保您的代碼注釋正確並說明其工作方式。
您要做的是將靜態方法與對象的上下文綁定,該對象要從靜態方法中調用。 您可以通過使用call
方法調用它來做到這一點:
class ABC extends Component {
static bar () {
this.foo();
}
foo () {
// function body
}
}
let instance = new ABC();
ABC.bar.call(instance);
或使用bind
如果您想傳遞回調等函數,則將其預綁定 ,可以這么說:
let instance = new ABC();
setTimeout(ABC.bar.bind(instance), 1000);
注意:默認情況下, this
引用您的類,而不是該類的實例(在我們綁定該實例后,它將引用一個實例),因此,如果要從第一個靜態方法中調用另一個靜態方法,則要使用完整的類名。
static bar () {
this.foo();
ABC.someOtherStaticMethod();
}
還請注意:如果您使用Typescript,則在引用實例方法時會出現錯誤,因為默認情況下, this
方法在您的靜態方法中引用您的類。 要解決此問題,您可能需要將此類型轉換為any
:
static bar () {
(<any>this).foo();
}
在這里,您告訴Typescript編譯器類似“假定this
不是我們的類,但我們不知道的東西”之類的東西,只是為了消除編譯時的錯誤。
您永遠不能從靜態方法(任何語言)訪問實例方法。 只有一個靜態方法,但是有多個實例,它如何知道要使用哪個實例( this
)?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.