javascript - 在 iffe 中访问 'this' 上下文

标签 javascript reactjs

假设我有一个带有方法 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/

相关文章:

javascript - jQuery UI 可排序 Portlet 强制向右或向左

javascript - 带有对象的 AngularJS 数组

javascript - 选择TD中具有特定ID的所有元素

reactjs - 将 tailwindcss 与 React 一起使用,清除后大小没有减小

javascript - Node.js Express router.post 返回 404 未找到

javascript - 从另一个文件进行 module.export-ing 后,函数未定义

ReactJS:IE11 不使用缓存数据发出新的 HTTP 请求

ajax - Reactjs:br标签和ajax请求

javascript - 如何更新 reducer 中对象的 1 个属性?

javascript - 添加onclick到动态创建的span标签