Shekspir
Shekspir

Reputation: 89

How to use "this" of class in "callbacks" in ES6?

I'm using Babel with ES2015. And want to use this inside callback inside method.

class baz {
  bar = "xxx";
  foo() {
    x(function() {
      console.log(this.bar);
    });
  }
}

function x(callback) {
  return callback();
}
var y = new baz();
y.foo();

https://jsfiddle.net/dnthehnt/7/ I'm getting

TypeError: this is undefined

because as far as I understand this refers to the callback function in x(). As a solution I use

class baz {
  bar = "xxx";
  foo() {
    var bar = this.bar;//<=====
    x(function() {
      console.log(bar);//<=====
    });
  }
}

function x(callback) {
  return callback();
}
var y = new baz();
y.foo();

https://jsfiddle.net/dnthehnt/6/ And get

xxx

This is solution, but if you have mass of code it's getting very confusing and hard to write. Is there any better solution for using this? Or any other discipline for ES6 for using callbacks and this.

Upvotes: 1

Views: 3539

Answers (1)

jlowcs
jlowcs

Reputation: 1933

Look into arrow functions, and especially the way this is handled by arrow functions in comparison to classic functions.

class baz {
  constructor() { this.bar = "xxx"; }
  foo() {
    x(() => {
      console.log(this.bar);
    });
  }
}

Your solution using classic functions would not work if bar was changed between the call to x and the call to the callback.

This is how you should do it with classic functions

class baz {
  constructor() { this.bar = "xxx"; }
  foo() {
    const self = this;
    x(function () {
      console.log(self.bar);
    });
  }
}

Or you could use bind, I suppose.

class baz {
  constructor() { this.bar = "xxx"; }
  foo() {
    x((function () {
      console.log(this.bar);
    }).bind(this));
  }
}

Upvotes: 8

Related Questions