我需要引用可能嵌套在其中的其他方法的方法。所有方法都属于同一个对象。下面的代码解释了我想要做的一切:具有嵌套方法的方法引用参数的方法
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');
}
}
我觉得它是如此远离正确的解决方案,任何想法如何使这更好的 - 如果没有这些参数?