微信小程序this和that的区别
时间: 2024-03-27 09:36:53 浏览: 37
在微信小程序中,this 和 that 都是指向当前页面对象的指针,但是它们的作用域不同。
this 指向当前使用的组件或者页面对象,它的作用域是当前函数作用域。在事件处理函数中,this 指向触发事件的组件对象。
that 通常是在函数作用域中声明一个变量,将 this 赋值给 that,用于保存 this 的作用域。因为在一些函数嵌套时,this 的作用域可能会发生改变,使用 that 可以避免作用域的改变。在事件处理函数中,that 通常用于保存 this 的作用域,以便在函数嵌套时能够正确访问到 this 对象。
例如,以下代码中的 that 用于保存 this 的作用域,以便在 success 回调函数中能够正确访问 this 对象:
```
Page({
data: {
message: 'Hello World!'
},
onLoad: function () {
var that = this;
wx.request({
url: 'https://example.com/api',
success: function (res) {
that.setData({
message: res.data.message
})
}
})
}
})
```
需要注意的是,微信小程序中的 this 和 that 只是指针,它们并不是 JavaScript 中的关键字或者保留字。在实际开发中,可以根据需要使用 this 或 that,以便正确访问当前页面对象的作用域。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)