1

Say i have a javascript class with a method, foo(). In another method, f.e componentDidMount, i want to access method foo() inside an iffe. How do i bind the 'this' context to be available inside the iffe?

I know i can this = self and use that, or use arrow syntax, but i would like to expand my knowledge of js & this, and thus do it with a proper binding. I've tried:

(function doSomething() {
  this.foo();
}.bind(this)())

But that doesn't work. Example code:

class Test extends React.Component {
  constructor(props) {}

  public componentDidMount() {
    (function doSomething() {
      this.foo();
    })();
  }

  foo() {
    // ...
  }
}
Tholle
  • 108,070
  • 19
  • 198
  • 189

2 Answers2

2

If you can't or don't want to use arrow functions, you can do the binding of your function to the outside context manually:

(function doSomething() {
  this.foo();
}.bind(this))();

The logic behind this keyword in javascript is discussed in detail in this question: How does the "this" keyword work? Or in this amazing book by Kyle Simpson: YDKJS: this & object prototypes

Gleb Kostyunin
  • 3,743
  • 2
  • 19
  • 36
0

Common pattern with iife is to use function arguments

class Test extends React.Component {
  constructor(props) {}

  public componentDidMount() {
    (function doSomething(self) {
      self.foo();
    })(this);
  }

  foo() {
    // ...
  }
}