在微信小程序中,可能會遭遇作用域的問題
一不小心就會犯錯,還一直看不出來=.=
是的,作為一個前端渣渣,我看了10min,在此記錄一下
注意看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)
}
}
});
},