Skip to content
Advertisement

ES6 Classes: Bind “this” to nested functions

I have multiple nested functions in a ES6 Class. Now I wonder how I can easily bind this of the class instance to all the subfunctions.

I know of…

subfunction1.bind(this)();

…but it feels like an awkward solution for multiple nested functions.

Does anyone know of a more elegant solution?

class User {
  constructor(name) {
    this.name = name;
  }

  mainFunction() {
    console.log(this.name);//"Paul"
    
    //In order for the nested functions to get "this" it is needed to bind it 
    //to the subfunction as shown below. Is there an easier way to achieve
    //this for all the subfunctions at once?
    
    subfunction1.bind(this)();
    subfunction2.bind(this)();
    
    function subfunction1() {
      console.log(this.name);//"Paul"
    }
    
    function subfunction2() {
      console.log(this.name);//"Paul"
    }
  }
}
const paul = new User("Paul");
paul.mainFunction();

Advertisement

Answer

You can use arrow functions. They work in rather a similar manner. The arrow notation will replace this with the value of the context of the arrow function’s scope.

class User {
  constructor(name) {
    this.name = name;
  }

  getSummary() {
    console.log(this.name);
    const subfunction1 = () => {
      console.log(this.name);//"Paul"
    }
    const subfunction2 = () => {
      console.log(this.name);//"Paul"
    }
    subfunction1();
    subfunction2();
  }
}
const paul = new User("Paul");
paul.getSummary();
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement