我需要引用可能嵌套在其中的其他方法的方法。所有方法都屬於同一個對象。下面的代碼解釋了我想要做的一切:具有嵌套方法的方法引用參數的方法
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');
}
}
我覺得它是如此遠離正確的解決方案,任何想法如何使這更好的 - 如果沒有這些參數?