微信小程序有没有避免频繁使用"const that = this"的技巧?

作者站长头像
站长
· 阅读数 8

微信小程序const that = this的疑问我看微信小程序异步方法回调的时候,有很多const that = this查了资料,说是因为原方法page调用,回调方法框架调用,this变了,所以用that来保留page那么有没有什么办法避免掉回调里频繁出现的const that = this

希望能有个方便的、框架式的解决办法——————已经解决了,箭头函数神无敌!我以前都不喜欢这类后来的写法,都很传统的用success: function() {...}今天这个问题刷新了我的认知,我以后就用success: () => {...}

回复
1个回答
avatar
test
2024-06-20

就是使用 🔗箭头函数 来保持后续业务代码的 this 指向是上层作用域中的 this

比如说,我们在一些 wx.xx 之类API的回调中使用:

page() {
  scanCode() {
    wx.scanCode({
      scanType: ['qrCode'],
      success: (res) => {
        console.log('获取扫码结果', res);
        this.setData({
          qrCode: res.result
        })
      },
      fail: (err) => {
        console.log('扫码失败', err);
      }
    });
  }
}

就不需要在外部在定义一个 const that = this 了。

在非小程序开发的时候也会有遇到这样的情况,也可以使用 箭头函数 改写回调函数

export default {
  ...
  methods: {
    onDeleteConfirm (id) {
      const that = this;
      this.$confirm({
        title: "确认删除",
        content: "是否删除选中文件?",
-       onOk: function () {
-          that.submitDeleteAction(id)
-       }
+       onOk: () => {
+          this.submitDeleteAction(id)
+       }
      })
    }
  }
}

很早之前 react 中也会使用 .bind() 或者 箭头函数 来指定 this 指向。

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

Handling Events – React

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容