1

I don't get how I'm supposed to get the reference of the app instance in the callback method. I've been looking at this: How to access the correct this inside a callback? but didn't really feel that I got something from it.

class App
{
  constructor()
  {
    this.imageHandler = new ImageHandler();
    this.imageHandler.loadImages(["img.jpg"], this.create);
  }

  create()
  {
    console.log("Here 'this' is undefined");
    console.log(this.imageHandler.images[0]);
  }
}

class ImageHandler
{
  constructor()
  {
    this.images = [];
  }

  loadImages(urls, callback)
  {
    urls.forEach((url) => {
      var img = new Image();
      this.images.push(img);
      img.onload = () => {
        if (this.images.length == urls.length) {
          callback();
        }
      }
      img.src = url;
    });
  }
}

So the clunky way could be chaining a reference to the original instance like this:

this.imageHandler.loadImages(["img.jpg"], this.create, this);

loadImages(urls, callback, self)

callback(self);

create(self)

console.log(self.imageHandler.images[0]);

But it seems like a really awkward way of doing it. Can I achieve it in another more elegant way?

Tc_
  • 505
  • 1
  • 6
  • 15
  • 1
    This question is definitely not a duplicate. If you read this question, you can see that it's at least somewhat related to ES6 classes. – Brad Nov 03 '18 at 02:39

1 Answers1

4

Instead of this:

this.imageHandler.loadImages(["img.jpg"], this.create);

Try this:

this.imageHandler.loadImages(["img.jpg"], this.create.bind(this));

The issue is that you're passing a reference to the method on the class, but it isn't bound to the instance in this unless you call .bind().

Brad
  • 159,648
  • 54
  • 349
  • 530