JavaScript类中函数内部调用另一个函数失败问题求助
问题解决:autoClicker函数未被调用的原因及修复
核心问题:函数调用语法错误
你写的this.autoClicker只是引用了函数对象本身,并没有触发函数执行。必须加上括号this.autoClicker()才能真正调用这个函数。
额外的this绑定问题
另外你的donutMaker方法是普通函数,作为addEventListener的回调时,this会指向触发事件的DOM按钮元素,而不是DonutMaker类的实例,这会导致该方法里的操作出错。可以通过箭头函数包裹或者在构造函数绑定this来解决。
修正后的完整代码
class DonutMaker { constructor() { this.donut_creater = document.getElementById("donut_creater"); // 修正donutMaker的this指向问题 this.donut_creater.addEventListener("click", () => this.donutMaker()); this.auto_clicker = document.getElementById("auto_clicker"); this.auto_clicker.addEventListener("click", this.autoClickerHandler); } donutMaker() { const selection = document.getElementById("donut_quantity"); let quantity = parseInt(selection.innerText) || 0; quantity += 1; selection.innerText = quantity; } autoClickerHandler = () => { const selection = document.getElementById("donut_quantity"); let updated_quantity = parseInt(selection.innerText) || 0; const new_quantity = updated_quantity - 1; if (updated_quantity >= 1) { selection.innerText = new_quantity; const selection2 = document.getElementById("auto_clicker_quantity"); let auto_clicker_quantity = parseInt(selection2.innerText) || 0; auto_clicker_quantity += 1; selection2.innerText = auto_clicker_quantity; // 修正函数调用语法,添加括号 this.autoClicker(); } else { console.log("Not Eligible"); } }; autoClicker = () => { console.log("Hello"); // console.log("Auto clicker"); }; } let obj = new DonutMaker();
额外优化建议
- 避免用
this存储临时变量和DOM元素,改用局部变量(比如const selection)更清晰,也减少不必要的实例属性占用。 - 解析文本转数字时加上
|| 0,防止初始值为空或非数字时出现NaN错误。
内容的提问来源于stack exchange,提问作者Ayan Khan
相关产品推荐
相关产品推荐

