做用域淺析

在微信小程序中,可能會遭遇做用域的問題
一不當心就會犯錯,還一直看不出來=.=
是的,做爲一個前端渣渣,我看了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

相關文章
相關標籤/搜索