假设我有一个带有方法 foo() 的 javascript 类。在另一种方法中,f.e componentDidMount,我想在 iffe 中访问方法 foo()。我如何绑定(bind) 'this' 上下文以在 iffe 内可用?
我知道我可以 this = self 并使用它,或者使用箭头语法,但我想扩展我对 js 和 this 的知识,从而通过适当的绑定(bind)来完成它。我试过:
(function doSomething() {
this.foo();
}.bind(this)())
但这行不通。示例代码:
class Test extends React.Component {
constructor(props) {}
public componentDidMount() {
(function doSomething() {
this.foo();
})();
}
foo() {
// ...
}
}
最佳答案
如果您不能或不想使用箭头函数,您可以手动将函数绑定(bind)到外部上下文:
(function doSomething() {
this.foo();
}.bind(this))();
javascript 中 this
关键字背后的逻辑在这个问题中有详细讨论:How does the "this" keyword work?或者在凯尔·辛普森 (Kyle Simpson) 的这本精彩书中:YDKJS: this & object prototypes
关于javascript - 在 iffe 中访问 'this' 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55119770/