Javascript JS-从同一类中的其他方法调用类中的方法
最近我开始练习javascript/jQuery。 我有一份班级调查问卷Javascript JS-从同一类中的其他方法调用类中的方法,javascript,jquery,class,methods,Javascript,Jquery,Class,Methods,最近我开始练习javascript/jQuery。 我有一份班级调查问卷 class Questionnaire { constructor (json, container) { // constructor stuff } processAnswers() { // Do something } showQuestionnaire() { // A lot of stuff happens he
class Questionnaire {
constructor (json, container) {
// constructor stuff
}
processAnswers() {
// Do something
}
showQuestionnaire() {
// A lot of stuff happens here
// HTML gets build in this method and added to an excisting container.
// The element with class 'button_confirm' gets generated here as well.
// this.container is an excisting HTML DOM-Object (Div)
$(this.container).find('.button_confirm').on('click', function () {
this.processAnswers();
});
}
}
一切进展顺利,但当我按下按钮并触发事件时,我得到一个错误,告诉我processAnswers不是一个函数
我做错了什么?为什么我不能从这里打电话给processAnswers?
这可能是一个简单的解决办法,但我看不出有什么错误
提前感谢。您需要在此处使用箭头函数,这是因为
此
将指向单击事件处理程序中的窗口对象,但您需要当前上下文
$(this.container).find('.button_confirm').on('click', (e)=> {
this.processAnswers();
});
或者在指向this.processAnswers()的函数前面声明一个
常量
。箭头函数更简洁。