如何将`this`上下文传递给自调用匿名函数而不将`this`存储在变量中?

问题描述 投票:1回答:1

理想情况下,我们可以使用Function.prototype.bind函数执行此操作。我不认为这里有一个明确的方法来使用胖箭头功能。 Ycombinator魔术?

这是我到目前为止所尝试的:

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

    this.write(value)
    return pump()
  })
}).bind(this)()
javascript anonymous-function self-invoking-function
1个回答
0
投票

这是我做的:

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
© www.soinside.com 2019 - 2024. All rights reserved.