zoukankan      html  css  js  c++  java
  • 作用域浅析

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

  • 相关阅读:
    c++ 左值和右值
    C++的顶层const和底层const的理解
    TCP/IP模型中的网络层
    有关TCP/IP模型中的网络接入层
    计算机网络协议与IPv4地址
    浅析计算机网络
    海思Android开发平台如何自定义update.zip内容
    Android平台RTL蓝牙适配偶现打不开问题调试笔记
    Android的SoundPool
    Android开发之IntentService
  • 原文地址:https://www.cnblogs.com/Lulus/p/8946091.html
Copyright © 2011-2022 走看看