javascript - 无法使用 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>
正如您在控制台中看到的,当我激活第二次按下按钮时,我得到“未定义”,但我真的不知道为什么会这样,因为“应用程序”没有被重新声明。
亲切的问候,贾斯珀
解决方案
这不是捕捉点击事件的正确方法。从您的 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>
推荐阅读
- android - Android Volley 缓存创建重复项
- javascript - 错误:[object HTMLParagraphElement],当从函数中分配变量时
- github - Codeship Pro/GitHub 触发器构建在“Ready For Review”或“PR Title Change”之上
- javascript - 带有多个参数的 Javascript 过滤
- postgresql - 如何计算 Postgresql 中特定日期最后 7 行的累积总和?
- git - 对未跟踪的文件使用 git auto stash 选项
- unity3d - 从 http 服务器获取文件时,我的统一程序卡住了
- docker - Nginx 无限重定向,使用 docker-compose 进行反向代理
- r - 在 R 中使用外部变量生成滚动预测
- node.js - npm 链接的信息保存在本地项目中的位置