小程序箭头函数

915 阅读1分钟

如果在小程序中直接使用箭头函数的话会导致 this 丢失。代码如下:

Page({    onLoad: () > {        console.log(this)         // 此时的 this 并不指向当前 page    }})

那么这种情况下,想要实现很多功能都很不方便了, 比如接受参数根据参数拉去信息等。

我的解决方案很简单,使用立即执行函数代码如下:

Page({    onLoad: function() {        let that = this        ;(async () => {            console.log(that)             // 使用that,that 的作用域依然是 page 对象            // 欢乐的调用其他的任何操作,还能享用异步同步写法            await that.login()            await that.query()        })();    }})
小程序箭头函数