javascriptanonymous-functionself-invoking-function

How can I pass `this` context to a self invoking anonymous function without storing `this` in a variable?


Ideally we can do this using the Function.prototype.bind function. I don't think there's a clear way to use a fat arrow function here either. Ycombinator magic?

This is what I tried so far:

(function pump () {
  return browserReadableStreamReader.read().then(({ done, value }) => {
    if (done) {
      return this.end()
    }

    this.write(value)
    return pump()
  })
}).bind(this)()

Solution

  • Here's what I did:

    const { PassThrough } = require('stream')
    /**
     * Google Chrome ReadableStream PassThrough implementation
     * @extends PassThrough
     */
    class BrowserPassThrough extends PassThrough {
      /**
       * @param {Object} options - options to pass to PassThrough
       * @param {ReadableStreamDefaultReader} browserReadableStreamReader - reader
       */
      constructor (options, browserReadableStreamReader) {
        super(options)
        this.reader = browserReadableStreamReader
        this.pump()
      }
    
      pump () {
        this.reader.read().then(({ done, value }) => {
          if (done) {
            return this.end()
          }
    
          this.write(value)
          this.pump()
        })
      }
    }
    module.exports = BrowserPassThrough