【问题标题】:JS - Calling method in class from other method in same class [duplicate]JS - 从同一类中的其他方法调用类中的方法[重复]
【发布时间】:2019-11-02 13:25:35
【问题描述】:

最近我开始练习 javascript/jQuery。 我有一份班级问卷。

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? 这可能是一个简单的修复,但我没有看到错误。

提前致谢。

【问题讨论】:

    标签: javascript jquery class methods


    【解决方案1】:

    这里需要使用箭头函数,因为this会指向click事件处理程序内部的window对象,但是你需要当前上下文

    $(this.container).find('.button_confirm').on('click', (e)=> {
                this.processAnswers();  
            });
    

    【讨论】:

    • 或者在指向this.processAnswers()的函数之前声明一个constant。箭头函数更简洁。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 2013-01-12
    相关资源
    最近更新 更多