Привязать это в экземпляре - PullRequest
0 голосов
/ 14 января 2019

У меня есть простой класс, обрабатывающий читаемый поток ответа Fetch:

class ProgressIndicator {

  constructor(res) {

    this.res = res;

    this.contentLength = parseInt(res.headers.get('content-length', 10));

    this.loaded = 0;

    return new Response(

      new ReadableStream({

        start(controller) {

          console.log(this);

          this.reader = this.res.body.getReader();

          this.readStream(controller);

        }

      })

    );

  }

Очевидно, что если я запишу это внутри функции запуска, я получу собственную функцию.

Есть идеи, как связать объект ProgressIndicator с функцией запуска?

1 Ответ

0 голосов
/ 14 января 2019

создать атрибут в классе ProgressIndicator, он будет ссылаться на область видимости класса.

 class ProgressIndicator {

  var selfScope = this;

  constructor(res) {

    this.res = res;

    this.contentLength = parseInt(res.headers.get('content-length', 10));

    this.loaded = 0;

    return new Response(

      new ReadableStream({

        start(controller) {

          console.log(selfScope);

          this.reader = this.res.body.getReader();

          this.readStream(controller);

        }

      })

    );

  }
...