最近我开始练习 javascript/jQuery。 我有一份类(class)调查问卷。
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
将指向点击事件处理程序内的窗口对象,但您需要当前上下文
$(this.container).find('.button_confirm').on('click', (e)=> {
this.processAnswers();
});
关于javascript - JS - 从同一类中的其他方法调用类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58671552/