JavaScript中如何在类的函数内调用另一个函数?代码调用失败求助
解决DonutMaker类中autoClicker函数调用无效的问题
核心问题
你写的this.autoClicker;只是引用了函数对象,并没有真正执行函数调用。要触发函数执行,必须加上调用括号:this.autoClicker();
修改关键代码
把autoClickerHandler里的调用语句替换为:
// 原无效代码 this.autoClicker; // 修改后可执行的调用 this.autoClicker();
额外修复潜在问题
你的donutMaker是普通类方法,直接绑定到click事件时,this会指向触发事件的DOM按钮元素,而非DonutMaker实例,后续访问this.selection等属性会出错。可以用两种方式修复:
方式1:将donutMaker改为箭头函数
donutMaker = () => { this.selection = document.getElementById("donut_quantity"); this.quantity = this.selection.innerText; this.updated_quantity = parseInt(this.quantity); this.updated_quantity += 1; this.selection.innerText = this.updated_quantity; };
方式2:在构造函数中绑定this到类实例
constructor() { this.donut_creater = document.getElementById("donut_creater"); // 绑定this确保方法内的this指向类实例 this.donutMaker = this.donutMaker.bind(this); this.donut_creater.addEventListener("click", this.donutMaker); this.auto_clicker = document.getElementById("auto_clicker"); this.auto_clicker.addEventListener("click", this.autoClickerHandler); }
完整修复后的代码
class DonutMaker { constructor() { this.donut_creater = document.getElementById("donut_creater"); this.donutMaker = this.donutMaker.bind(this); this.donut_creater.addEventListener("click", this.donutMaker); this.auto_clicker = document.getElementById("auto_clicker"); this.auto_clicker.addEventListener("click", this.autoClickerHandler); } donutMaker() { this.selection = document.getElementById("donut_quantity"); this.quantity = this.selection.innerText; this.updated_quantity = parseInt(this.quantity); this.updated_quantity += 1; this.selection.innerText = this.updated_quantity; } autoClickerHandler = () => { this.selection = document.getElementById("donut_quantity"); this.quantity = this.selection.innerText; this.updated_quantity = parseInt(this.quantity); this.new_quantity = this.updated_quantity - 1; if (this.updated_quantity >= 1) { this.selection.innerText = this.new_quantity; this.quantity = this.new_quantity; this.selection2 = document.getElementById("auto_clicker_quantity"); this.auto_clicker_quantity = this.selection2.innerText; this.auto_clicker_quantity = parseInt(this.auto_clicker_quantity); this.auto_clicker_quantity_updated = this.auto_clicker_quantity + 1; this.selection2.innerText = this.auto_clicker_quantity_updated; // 修复后的函数调用 this.autoClicker(); } else { console.log("Not Eligible"); } }; autoClicker = () => { console.log("Hello"); // console.log("Auto clicker"); }; } let obj = new DonutMaker();
内容的提问来源于stack exchange,提问作者Ayan Khan
相关产品推荐
相关产品推荐

