Angel Luis
Angel Luis

Reputation: 557

Bind this in an instance

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?

Upvotes: 2

Views: 117

Answers (2)

Josh McGee
Josh McGee

Reputation: 552

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

Upvotes: 0

Sameer
Sameer

Reputation: 519

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

        }

      })

    );

  }

Upvotes: 1

Related Questions