javascript - ES6中如何防止覆盖上下文this

标签 javascript jquery ecmascript-6 this jquery-events

How to prevent jquery to override "this" 非常相似但在 ES6 中。

这是我的课:

class FeedbackForm {
  constructor(formEl) {
    this.$form = $(formEl)
    this.$form.submit(this.sendStuff)

    this.alerts = $('#something');
  }

  /**
   * Sends the feedback
   * @param {Event} e
   */
  sendStuff(e) {
    e.preventDefault()

    if (this.alerts.length) {
      window.alert('Notice... stuff')
    }

    $.ajax({
      type: this.$form.prop('method'),
      url: this.$form.prop('action'),
      data: this.$form.serialize()
    }).done(() => window.location.reload(true))
  }
}

sendStuff method 是表单的事件处理程序,jQuery 使用 Function.prototype.apply 调用它。我相信。因此,this里面sendStuff被 jQuery 应用的事件目标覆盖,我无法访问 this.alerts或任何其他属性方法。

我不确定是否可以申请 var that = this这里有技巧或者我该如何解决这个问题?

最佳答案

您可以使用arrow function :

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value

这应该可以做到:

this.$form.submit(e => this.sendStuff(e));

关于javascript - ES6中如何防止覆盖上下文this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34623259/

相关文章:

PHP/MySql 从两个不同的表中获取值

javascript - 类中的箭头函数

javascript - 如何获取两个输入事件内两个不同函数内且都在本地范围内的两个变量的总和?

html - 自定义滚动条文本 chop 的问题

javascript - 为什么 `super` 关键字属性在 ES6 类中返回未定义?

javascript - 安装 babel 后我得到一个未声明变量的异常

javascript - 增强对象字面量中的对象解构

javascript - 如何从 Active Class 获取类别 ID 并传递给 Post 查询

javascript - 未捕获的类型错误 : Cannot read property 'length' of undefined JQUERY autocomplete

jquery - SlideUp() 导致元素消失(在 IE10 中)