小程序的this指向问题

2021-06-30  本文已影响0人  KevinLee0424

小程序的this指向的是window,一般要在方法里重新定义的

onLoad: function (options) {
   let _this = this;    //在此时this指的是window,把其赋给_this
   wx.request({
     url: '某地址',
     method:"get",
     data: {
       msg: {
         "buyerIdCard": "某证",
         "status":"yes"
       }
     },
     header: {
       "Content-Type": "application/json;charset=UTF-8"
     },
     success:function(res){
      //此处注意一点:小程序属于单向数据流,数据的双向绑定,需要借助于_this.setData函数进行重新赋值
       _this.setData({       //在此就可直接用data中的属性了
        listArr:res.data.msg
       })
     }
   })
  },

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

另外一种方法:使用 箭头函数

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

控制台显示这两个指向相同
原因: 箭头函数中this指向外层作用域,

上一篇下一篇

猜你喜欢

热点阅读