微信小程序中的this

在微信小程序中我们可以用this改变页面中的值:

setPlain: function(e) {
    this.setData({
      plain: !this.data.plain
    })
  },

但是在使用的过程中例如出现下面这种情况就会报错:

/**
   * 页面的初始数据
   */
  data: {
    ID: 10
  },

//在函数中更改data中的值
test: function() {
    console.log(this.data.ID)


    function testFun() {
    }

    testFun()
  }
这样可以打印出ID的值,但是我问在testFun中再次打印就会报错:
test: function() {
    console.log(this.data.ID)


    function testFun() {
      console.log(this.data.ID)
    }

    testFun()
  }


//Error:
Cannot read property 'data' of undefined;at pages/test/test page test function
TypeError: Cannot read property 'data' of undefined


这是因为this是指向当前的对象,随着上下文作用域的切换this的执行this的指向会发生改变,我们可以先保存一份this的值然后再使用:

test: function() {
var that = this

console.log(that.data.ID)


function testFun() {
  console.log(that.data.ID)
}

testFun()

}


可以在前端页面中绑定data中的值,然后在程序中更改组件的样式:

https://developers.weixin.qq.com/miniprogram/dev/component/button.html

猜你喜欢

转载自blog.csdn.net/gmq_syy/article/details/80178999