2017-10-10 93 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