How to retain 'this' in a callback method?

前提是你 提交于 2020-12-13 07:53:06

问题


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?


回答1:


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().



来源:https://stackoverflow.com/questions/53127828/how-to-retain-this-in-a-callback-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!