美文网首页
4.【已解决】TypeError: Cannot read pr

4.【已解决】TypeError: Cannot read pr

作者: TensorFlow开发者 | 来源:发表于2019-05-26 14:04 被阅读0次

场景

自己在调用wx.getSystemInfo({})时,开发工具自动补全了代码。在success回调中按照以往的写法调用this.setData({ });时,报错:TypeError: Cannot read property 'setData' of undefined。

相关代码如下:

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getSystemInfo({
      success: function (res) {
        console.log(res);
        this.setData({
          system_info: res.brand,
        });
      },
      fail: function (res) {
        this.myShowError("获取手机系统信息")
      },
      complete: function (res) { },
    })

  },

仔细对比和之前绑定事件调用this.setData({ });时相比,调用方式并没有什么差别。因为刚接触小程序开发,success: function (res) {};这种写法没见过,所以猜想问题可能出在这里了。该用以下方式即可正常使用。

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getSystemInfo({
      success: (res) => {
        console.log(res);
        this.setData({
          system_info: res.brand,
        });
      },
      fail: function (res) {
        this.myShowError("获取手机系统信息")
      },
      complete: function (res) { },
    })

  },

解决方案

success: function (res) {
   this.setData({})
}

改成了:

success: (res) =>  {
   this.setData({})
}

【原因分析】
为什么呢?
因为两种写法this指向不同。

success: (res) => {
        console.log("(res) => { }时:" + this);
      },

--------------

success: function (res){
        console.log("function (res)时:" + this);
       },

对比分析:

function (res)时:undefined
 (res) => { }时:[object Object]

function (res)写法时 ,thisundefined未定义的。
(res) => { }写法时thisObject

【分析总结】
1、如果函数作为对象的方法调用,this指向的是这个上级对象,即调用方法的对象。
2、如果是构造函数中的this,则this指向新创建的对象本身。

相关文章

网友评论

      本文标题:4.【已解决】TypeError: Cannot read pr

      本文链接:https://www.haomeiwen.com/subject/qywxtctx.html