2017-10-10 100 views
0

我需要引用可能嵌套在其中的其他方法的方法。所有方法都屬於同一個對象。下面的代碼解釋了我想要做的一切:具有嵌套方法的方法引用參數的方法

class SomeClass { 

    functionPop(this.mainFunc); 

    functionPop(func) { 
    func(); 
    } 
    mainFunc() { 
    console.log('This will be printed'); 
    this.nestedFunc(); //Here is an error 
    } 
    nestedFunc() { 
    console.log('We didnt reach this point'); 
    } 

} 

錯誤告訴我,存在一個問題,這是未定義的。我明白mainFunc方法中的「this」這個詞不會引用SomeClass的對象。我知道我可以修復它做這樣的事情:

class SomeClass { 

    functionPop(this.mainFunc); 

    functionPop(func,nestedFunction) { 
    func(nestedFunction); 
    } 
    mainFunc(nestFunc) { 
    console.log('This will be printed'); 
    nestedFunction(); 
    } 
    nestedFunc() { 
    console.log('Here we are successfully - this will be printed'); 
    } 

} 

我覺得它是如此遠離正確的解決方案,任何想法如何使這更好的 - 如果沒有這些參數?

回答

1

無論何時,如果您傳遞函數參考functionPop(this.mainFunc);,函數內部的上下文(this)將根據調用方式發生更改。在這種情況下,functionPop內的上下文被調用爲func() - 因此this將爲undefined

爲了解決這個問題,你可以用arrow function包裝你的功能,當你將它們 - 這將保存上下文:

functionPop(() => this.mainFunc()); 

或者使用Function.bind設置上下文:

functionPop(this.mainFunc.bind(this)); 

另見:Red Flags for this

1

在Javascript中,'this'可能根據調用上下文而不同。在你的情況下,你正在失去呼叫上下文,這就是錯誤出現的原因。

有幾種方法來解決這個問題:

  1. 使用箭頭功能。與通常的相反,它們不會創建自己的上下文(ES6功能) 。
  2. 使用'綁定'綁定需要的上下文。

欲瞭解更多詳細信息,以實例和利弊/可能的方案的利弊檢查此鏈接:

https://github.com/Microsoft/TypeScript/wiki/%27this%27-in-TypeScript