In the WeChat applet, you may encounter the problem of scope. If you are
not careful, you will make mistakes, and you can't see it all the time =.=
Yes, as a front-end slag, I watched it for 10 minutes and recorded it here
Pay attention to the location and writing of this
<view class="container">
<button bindtap="testScope1">Test 作用域(正确1)</button>
</view>
<view class="container">
<button bindtap="testScope2">Test 作用域(正确2)</button>
</view>
<view class="container">
<button bindtap="testScope3">Test 作用域(错误)</button>
</view>
testScope1:function(){
//this在外面
var that = this;
//没有绑定appId,这里返回的code是一个模拟code
wx.login({
success: function (res) {
console.log(res)
if (res.code) {
//调用后端接口获得sessionkey
util.postRequest('/AccountForMiniProgram/WechatGetSessionKey', { id: res.code }, that, "sessionKey");
} else {
console.log('登录失败!' + res.errMsg)
}
}
});
},
testScope2:function(){
//参考资料:http://jsrocks.org/cn/2014/10/arrow-functions-and-their-scope
//使用=> 则作用域正确
wx.login({
success: (res)=> {
//this在里面
var that = this;
console.log(res);
if (res.code) {
//调用后端接口获得sessionkey
util.postRequest('/AccountForMiniProgram/WechatGetSessionKey', { id: res.code }, that, "sessionKey2");
} else {
console.log('登录失败!' + res.errMsg)
}
}
});
},
testScope3:function(){
wx.login({
success: function (res) {
//this在里面
//报错:that.setData is not a function 因为此时作用域已经改变
var that = this;
console.log(res);
if (res.code) {
//调用后端接口获得sessionkey
util.postRequest('/AccountForMiniProgram/WechatGetSessionKey', { id: res.code }, that, "sessionKey");
} else {
console.log('登录失败!' + res.errMsg)
}
}
});
},
sample code
https://github.com/zLulus/NotePractice/blob/dev3/MiniProgramDemo/pages/index/index.js
Interface:
https://github.com/zLulus/NotePractice/blob/dev3/Website/DotNetFramework/NotePractice/Controllers /AccountForMiniProgramController.cs