2

I've a simple class handling the readable stream of a Fetch response:

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);

        }

      })

    );

  }

Obviously if I log this inside the start function, I get the own function.

Any idea of how I can bind the ProgressIndicator object to the start function?

Liam
  • 27,717
  • 28
  • 128
  • 190
Angel Luis
  • 487
  • 2
  • 5
  • 19
  • 1
    create attribute within ProgressIndicator self = this; and log (self); will refer to class scope – Sameer Jan 14 '19 at 11:29
  • @Sameer I've used self and it works, but it's not dangerous if I create more than one instances? Or it creates a new self for each instance? – Angel Luis Jan 14 '19 at 11:36
  • It will create new instance for each. Unless you declare self as Static. – Sameer Jan 14 '19 at 11:39

2 Answers2

1

create attribute within ProgressIndicator class, it will refer to class scope.

 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);

        }

      })

    );

  }
Sameer
  • 509
  • 3
  • 16
  • create attribute within ProgressIndicator self = this; and log (self); will refer to class scope – Sameer Jan 14 '19 at 11:52
0

an alternate solution could be to define start as an arrow function because arrow functions don't have their own binding to 'this'

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);
        }
      })
    );
  }
Josh McGee
  • 443
  • 6
  • 16