[英]how to call outer class function from inner function in Javascript?
class Outer{
private outFunction(){
console.log("Okay!");
}
public functionWeCall(){
function innerFunction(){
this.outFunction(); //That doesn't work
}
}
}
我試圖將代碼拆分為函數,以提高可讀性。 但這不起作用,如何從內部函數調用外部類函數?
這是一個范圍問題。 當你到達functionWeCall()
, this
開始引用那個函數而不是類,因此outFunction()
在this
上不存在。 典型的解決方法可能如下所示:
class Outer {
private outFunction() {
console.log("Okay!");
}
public functionWeCall() {
let _this = this;
function innerFunction() {
_this.outFunction();
}
}
}
...但我寧願建議重新處理整個事情,這樣你就沒有這樣的嵌套函數。
編輯:正如@Aluan Haddad 所建議的,這是同樣的事情,但有一個箭頭函數:
class Outer {
private outFunction() {
console.log("Okay!");
}
public functionWeCall() {
() => {
this.outFunction();
}
}
}
...如果您希望內部函數仍然可調用,請將其分配給一個變量:
class Outer {
private outFunction() {
console.log("Okay!");
}
public functionWeCall() {
let innerFunction = () => {
this.outFunction();
}
innerFunction(); // this could be anywhere in the scope of functionWeCall()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.