与 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/