【发布时间】:2016-01-05 23:42:00
【问题描述】:
与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 方法是表单的事件处理程序,我相信 jQuery 使用Function.prototype.apply 调用它。因此,sendStuff 中的 this 被 jQuery 应用的事件目标覆盖,我无法访问 this.alerts 或任何其他属性方法。
我不确定是否可以在此处应用 var that = this 技巧或如何解决此问题?
【问题讨论】:
标签: javascript jquery ecmascript-6 this jquery-events