1

I've seen several questions about using "this" in classes and functions, but I don't think I've seen what I'm looking for in particular.

My situation is:

I'm calling a function from a third-party library in a class method. However, the third-party library function is calling callback.bind(this), and I need to have access to the context it's binding.

But I also want to be able to access class properties. Is this possible? If not, what are some potential workaround? Code outline looks something like:

class MyClass {
  myProperty = 'something';

  myMethod() {
    console.log(this.myProperty);
  }

  otherMethod() {
     thirdPartyLibrary.functionRequiringCallback(function() {
       this.MyMethod(); //undefined
       this.requiredThirdPartyFunction(); //"this" refers to thirdPartyLibrary
     });
  }
}

I could certainly make the callback an arrow function so that "this" refers to the class-scope, but then I won't have access to "requiredThirdPartyFunction".

Any help would be appreciated.

ZenPylon
  • 518
  • 4
  • 11

2 Answers2

3

When you want a reference to your instance this, you can always use the old that = this assignment. You assign this to a variable in the scope (that usually), and then you can reference it inside the callback.

otherMethod() {
  const that = this; // set a reference to the instance this

  thirdPartyLibrary.functionRequiringCallback(function() {
    that.MyMethod(); // that refers to your class instance this
    this.requiredThirdPartyFunction(); //"this" refers to thirdPartyLibrary
  });
}

Another option is to bind myMethod, by using an arrow function or Function#bind, and then assign the bound method to a variable:

class MyClass {
  myProperty = 'something';

  myMethod = () => console.log(this.myProperty);

  otherMethod() {
     const myMethod = this.myMethod; // assign the bound method to a variable

     thirdPartyLibrary.functionRequiringCallback(function() {
       MyMethod(); // will be invoked with original this
       this.requiredThirdPartyFunction(); //"this" refers to thirdPartyLibrary
     });
  }
}
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Wow, this did it for me. Which means my question was basically a duplicate of all the other similar questions...thanks for clarifying! – ZenPylon Jul 23 '17 at 23:07
1

There are not so many options here. Since there is only one this, it can be either lexical:

  otherMethod() {
     thirdPartyLibrary.functionRequiringCallback(() => {
       this.MyMethod();
       thirdPartyLibrary.requiredThirdPartyFunction();
     });
  }

Or dynamic:

  otherMethod() {
     const _this = this;
     thirdPartyLibrary.functionRequiringCallback(function() {
       _this.MyMethod();
       this.requiredThirdPartyFunction();
     });
  }

The first option is more readable and is likely a better choice, since it's not obvious from the code above that this === thirdPartyLibrary inside callback.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565