微信小程序初探之this关键字

53 阅读1分钟

在微信小程序开发过程中,有时需要在函数中访问页面中定义的一些数据,或者调用页面中定义的一些函数,此时可以通过this关键字来实现。this关键字代表当前页面对象。下面通过代码演示this关键字的使用,具体代码如下。

Page({ 
  data: { num: 1 },               // 定义data数据 
 test: function () {              // 定义test()函数 
    console.log('test()函数执行了') 
},  
  onLoad: function () { 
    console.log(this.data.num)    // 通过this关键字访问data中的num数据 
    this.test()                   // 通过this关键字调用test()函数 
  } 
}) 

上述代码演示了如何在onLoad()函数中通过this关键字访问data中的num数据并调用test()函数。程序运行后,在控制台中可以看到程序输出了this.data.num的值“1”和“test()函数执行了”。