我是一名獨立開發者, 接小程序外包
歡迎加入我的小程序交流群 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()
})();
}
})