微信小程序Cannot read property 'setData' of undefined问题解决

今天写小程序,需要读取窗口高度然后设置scroll-view高度,在this.setData时报错“Cannot read property 'setData' of undefined”,代码如下:

onShow: function () {
    wx.getSystemInfo({
      success: function(res) {
        this.setData({
          scrollHeight:res.windowHeight-100*res.windowHeight/750
        });
      },
    });
  },

原因是getSystemInfo函数体中的this指向闭包,而不是page对象,所以需要在函数外定义this才能用。

onShow: function () {
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          scrollHeight:res.windowHeight-100*res.windowHeight/750
        });
        console.log(that.data.scrollHeight);
      },
    });
  },

另外一种解决方法是使用箭头函数,ES6规定箭头函数没有自己的this,导致内部的this指向外层代码的this(最近的this),这个指向在定义时就已经确定,不会在执行时再指向执行环境的this。

因此可以:

  onShow() {
    wx.getSystemInfo({
      success: (res) => {
        //80为顶部搜索框区域高度 rpx转px 屏幕宽度/750
        this.setData({
          scrollHeight: res.windowHeight - (100 * res.windowWidth / 750)
        });
      }
    })
  },

普通函数this和箭头函数this对比分析详细见这篇文章https://segmentfault.com/a/1190000014027459

关于this的指向

总的来说:

this指向执行主体

分几种情况:

  1. 普通函数执行时,如果没有执行主体,在非严格模式下指向window,在严格模式下指向undefined。
  2. 箭头函数没有this,它继承上下文的this。
  3. 构造函数里的this指向生成的实例对象。
  4. 事件绑定函数中的this指向当前操作的元素。
  5. call, apply, bind把函数中的this改为指定的执行对象。

你可能感兴趣的:(小程序)