小程序中的箭头函数

我是一名独立开发者, 接小程序外包
欢迎加入我的小程序交流群 wx: guzhan321 备注:小程序

如果在小程序中直接使用箭头函数的话会导致 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()
        })();
    }
})
原文地址:https://www.cnblogs.com/shixinglong/p/13130694.html