如果在小程序中直接使用箭头函数的话会导致 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()
})();
}
})
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69923331/viewspace-2698726/ ,如需转载,请注明出处,否则将追究法律责任。