首页 > 微信 > 详细

微信小程序,this指向问题

时间:2020-03-02 09:50:19      阅读:248      评论:0      收藏:0      [点我收藏+]

写wx.request函数的sucess返回时,需要更改data里面的属性值,this.setData遇到了undefined报错

根据网上博客方法,更改如下:

方法一:设置一个传值变量that

 1 onLoad: function (options) {
 2     var that=this;    //在此时this指的是window,把其赋给that
 3    wx.request({
 4      url: 某地址,
 5      method:"get",
 6      data: {
 7        msg: {
 8          "buyerIdCard": "某证",
 9          "status":"yes"
10        }
11      },
12      header: {
13        "Content-Type": "application/json;charset=UTF-8"
14      },
15      success:function(res){
16        that.setData({       //在此就可直接用data中的属性了
17         listArr:res.data.msg
18        })
19      }
20    })
21   },

原因:回调函数success中的this显示undefined,需要将外层this传进来。至于为啥会报undefined,有人给出解释是this指向回调函数本身。挖个坑

 

方法二:使用箭头函数:

   success:(res)=>{
       console.log(this);
       console.log(that);
       this.setData({
        listArr:res.data.msg
       })
     }

 控制台显示这两个指向相同

原因:箭头函数中this指向外层作用域,例子:

var obj = {
  foo() {
    console.log(this);
  },
  bar: () => {
    console.log(this);
  }
}

obj.foo() // {foo: ƒ, bar: ƒ}
obj.bar() // window

 

参考博客内容:1. https://www.cnblogs.com/jjzz1234/p/11620055.html

                         2.https://blog.csdn.net/lwqBrell/article/details/89219364

微信小程序,this指向问题

原文:https://www.cnblogs.com/xmjs/p/12393310.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!