在微信小程序中,可能会遭遇做用域的问题
一不当心就会犯错,还一直看不出来=.=
是的,做为一个前端渣渣,我看了10min,在此记录一下前端
注意看this的位置和写法问题git
<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) } } }); },
示例代码-index.js
接口github