作用域浅析

在微信小程序中,可能会遭遇作用域的问题
一不小心就会犯错,还一直看不出来=.=
是的,作为一个前端渣渣,我看了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)
        }
      }
    });
  },

示例代码

示例代码-index.js
接口

原文地址:https://www.cnblogs.com/Lulus/p/8946091.html