原文:https://www.sunzhongwei.com/es6-arrow-function-let-the-let-that-this-go-to-dead
调试小程序的时候,发现清空本地全部数据缓存之后,报错
thirdScriptError
this.login is not a function;at App onShow function;at api refreshSession fail callback function
TypeError: this.login is not a function
at Function.fail (http://127.0.0.1:9973/appservice/app.js:31:14)
at Object.fail (
第一眼愣是没发现问题,仔细一看 at api refreshSession fail callback function 我就明白了
// 检测微信登录态是否失效
wx.checkSession({
success: function () {
console.log("Good session!");
},
fail: function () {
console.log("Bad session!");
// 登录态过期
this.login()
}
})
回调函数里使用了 this 。。。
这是每个写 js 人的痛,也是我之前一直讨厌用 js 的重要原因之一。因为很容易就忽视了 this 的使用。
但是自从接触 weex,用了一段时间 ES6 之后,发现箭头函数真是完美解决 that/this 地狱问题。
fail: () => {
console.log("Bad session!");
// 登录态过期
this.login()
}
箭头函数的参数
没有参数
callback_func_name: () => {
// do something
}
一个参数
callback_func_name: var1 => {
// do something
}
多个参数
callback_func_name: (var1, var2) => {
// do something
}