const that = this 作用
时间: 2024-05-31 09:14:54 浏览: 14
在 JavaScript 中,const 关键字用于声明一个只读的常量。而在这个语句中,const that = this 的作用是将当前上下文的 this 对象赋值给一个常量 that,以便在后续的代码中能够使用该常量来访问 this 对象。这是因为在 JavaScript 中,this 的值是动态的,在不同的上下文中可能会指向不同的对象,而使用常量来保存 this 的值能够避免在后续的代码中出现 this 指向不正确的情况。通常在需要在回调函数或者异步操作中访问 this 对象时,使用 const that = this 这种方式是非常常见的。
相关问题
优化精简这段代码 currentStoreDistance() { const { longitude, latitude, big_stores } = this.data const stores = big_stores const origin = `${longitude},${latitude}` const destination = `${stores.longitude},${stores.latitude}` const that=this this.data.myAmapFun.getDrivingRoute({ origin, destination, success(data) { stores.distance = Math.round(data.paths[0].distance / 100) / 10 that.setData({ big_stores:stores }) } }) }
可以优化的地方有:
1. 将 destructuring 和赋值合并成一行;
2. 不需要将 `big_stores` 赋值给 `stores`,直接使用 `big_stores` 即可;
3. 将 `const that = this` 改为箭头函数;
4. 使用对象解构简化 `data.paths[0].distance` 的访问;
5. 使用模板字符串简化字符串拼接。
优化后的代码如下:
```
currentStoreDistance() {
const { longitude, latitude, big_stores } = this.data;
const origin = `${longitude},${latitude}`;
const destination = `${big_stores.longitude},${big_stores.latitude}`;
this.data.myAmapFun.getDrivingRoute({
origin,
destination,
success: (data) => {
const { distance } = data.paths[0];
big_stores.distance = Math.round(distance / 100) / 10;
this.setData({ big_stores });
}
});
}
```
解释一下:takePhoto() { console.log('----拍照') const that = this const ctx = wx.createCameraContext() ctx.takePhoto({ quality: 'high', success: (res) => { this.photoRes = res // console.log(this.photoRes) this.showCamera = false
这段代码是用于微信小程序中使用相机进行拍照的功能。具体解释如下:
1. `wx.createCameraContext()` 用于创建相机的上下文,返回一个相机上下文对象。
2. `ctx.takePhoto()` 方法用于触发相机的拍照操作,其中可以设置拍照质量等参数。该方法会返回一个 `success` 回调函数,在拍照成功后会将拍照结果作为参数传入该回调函数。
3. `this.photoRes = res` 将拍照结果保存到 `this.photoRes` 变量中,以便进行后续的处理。
4. `this.showCamera = false` 用于隐藏相机界面,展示拍照结果。
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)