【问题标题】:this inside an async object method [duplicate]这在异步对象方法中[重复]
【发布时间】:2017-10-23 22:12:48
【问题描述】:

我使用 babel-polyfill/babel-preset-es2017 创建了一个使用异步函数方法的对象,但是我遇到了this 的问题:

let obj = () => {
    return {
        doAsync: async () => {
            let thing = await longProcess()
            return this.transform(thing)
        },

        transform: (thing) => {
            return psuedoCodeTransform(thing)
        }
    }
}

let instance = obj()
instance.doAsync()
// TypeError: cannot read property 'transform' of undefined`.

这是 ES2017 中描述的东西,一个 babel-polyfill/regeneratorRuntime 陷阱吗?

【问题讨论】:

  • 这与async/await无关,与箭头函数无关。
  • ES7 !== ES2017 ...

标签: javascript async-await this babeljs ecmascript-2017


【解决方案1】:

Arrow functions do not create their own context。他们没有自己的thisthis 将引用封闭范围的上下文。在这种情况下(没有双关语),thisinstance 完全不同。

如果您在doAsync 中记录this,您会注意到它是window 全局。

【讨论】:

  • 有趣。我在 Angular 服务构造函数中执行此操作,它给了我console.log(this) // undefined。这就是让我失望的原因。
【解决方案2】:

Joseph the Dreamer 的回答显然是完全正确的,但由于我通过示例工作得最好,这里是您的代码更改,它应该可以正常工作。请注意,唯一的变化实际上是将doAsync 定义为普通函数而不是箭头函数:

let obj = () => {
    return {
        doAsync: async function() {
            let thing = await longProcess()
            return this.transform(thing)
        },

        transform: (thing) => {
            return psuedoCodeTransform(thing)
        }
    }
}

let instance = obj()
instance.doAsync()
// TypeError: cannot read property 'transform' of undefined`.

【讨论】:

  • 或者只是async doAsync() { ... }。我不明白为什么有人想在对象文字中使用箭头函数(当然,除非this)。方法定义更短。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-01
  • 2018-02-24
  • 2021-09-25
  • 2015-03-29
  • 1970-01-01
  • 2014-09-28
  • 1970-01-01
相关资源
最近更新 更多