微信小程序,this指向问题

写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