首页 > 解决方案 > 无法使用 onclick 函数访问先前在类上设置的变量

问题描述

所以我试图通过使用类和一个 init 函数来组织我的 javascript 项目,现在我遇到了这个我以前从未遇到过的奇怪问题。这是我的代码:

class App {
    constructor() {
        this._username;
    }

    authenticate() {
        this._username = "test";
    }

    submitForm() {
        console.log(this._username);
    }
}

const init = function () {
    const app = new App();

    document.getElementById("authenticationVerify").onclick = app.authenticate;
    document.getElementById("btnSendSMS").onclick = app.submitForm;
}

window.onload = init;

和 HTML(简体)

<body>
    <main>
        <form id="formSendSMS">
            <input type="button" name="send" id="btnSendSMS" value="Versturen">
        </form>

        <div id="authentication-prompt">
            <form>
                <input type="button" name="login" id="authenticationVerify" value="Log in" class="button blue">
            </form>
        </div>
    </main>
    <script src="js/mainBack.js" type="text/javascript"></script>
</body>

</html>

正如您在控制台中看到的,当我激活第二次按下按钮时,我得到“未定义”,但我真的不知道为什么会这样,因为“应用程序”没有被重新声明。

控制台中的“未定义”

亲切的问候,贾斯珀

标签: javascripthtmlclassclosures

解决方案


这不是捕捉点击事件的正确方法。从您的 js 代码中,我成功地制作了一个工作示例。

此外,JS 函数不能在没有括号的情况下调用。这里给出了一个很好的例子。

class App {
    constructor() {
        this._username;
    }

    authenticate() {
        this._username = "test";
    }

    submitForm() {
        console.log(this._username);
    }
}

const init = function () {
    const app = new App();

 
    document.getElementById("authenticationVerify").onclick = function(e){app.authenticate()};
    document.getElementById("btnSendSMS").onclick = function(e){app.submitForm()};
}


window.onload = init;
<button id="authenticationVerify">AUTH</button>
<button id="btnSendSMS">SMS</button>


推荐阅读