Electron计算器出现Cannot read 'toString'/'isNan' of undefined报错
报错根因定位
所有异常均来自代码实现细节缺陷,无Electron框架相关问题,具体对应关系如下:
- 实例运算属性未初始化(直接触发
calc.js:16的toString报错)
Calculator类的构造函数仅绑定了两个DOM文本元素引用,未初始化this.currentOperand、this.previousOperand、this.operation三个核心运算属性。首次触发点击事件时,从未执行过clear()方法完成赋值,上述属性值为undefined。此时无论执行this.currentOperand.includes('.')还是this.currentOperand.toString(),都会直接抛出读取undefined属性的异常。 - 方法名大小写、变量名拼写错误(触发isNaN相关异常)
- JS原生数值判断方法为
isNaN(),代码中多处误写为isNan(),会直接抛出方法未定义的ReferenceError compute()方法中判断当前运算值的变量误写为curent(漏写字母r),属于未定义变量getDisplayNumber()方法拼接返回值时,误将已声明的integerDisplay写为intgerDisplay(漏写字母e),属于未定义变量
- JS原生数值判断方法为
- 类方法内错误引用全局作用域变量
updateDisplay()方法中调用getDisplayNumber(currentOperand)时,未加this.前缀,此处实际取到的是全局作用域下的DOM元素,而非类实例存储的运算数值,会导致显示逻辑完全错误,甚至触发额外的解析异常。 - 冗余全局变量定义
类外重复定义了与previousOperandTextElement、currentOperandTextElement完全等价的DOM查询变量previousOperand、currentOperand,极易造成后续代码的作用域混淆。
修复方案
按以下步骤修改后所有异常即可消除:
- 补充构造函数内的运算属性初始化
直接在构造函数中调用已有的clear()方法完成属性赋值,无需重复写初始化逻辑:constructor(previousOperandTextElement, currentOperandTextElement) { this.previousOperandTextElement = previousOperandTextElement this.currentOperandTextElement = currentOperandTextElement // 新增:初始化所有运算属性,避免undefined this.clear() } - 修正所有拼写、大小写错误
- 全局替换所有
isNan为正确写法isNaN compute()方法中的isNaN(curent)改为isNaN(this.currentOperand),直接使用实例属性,无需单独声明局部变量getDisplayNumber()方法中拼接返回值的intgerDisplay改为integerDisplay
- 全局替换所有
- 修正updateDisplay的变量引用错误
将方法内读取当前运算值的代码改为引用类实例属性:// 原错误代码 // this.currentOperandTextElement.innerText = this.getDisplayNumber(currentOperand) // 修复后 this.currentOperandTextElement.innerText = this.getDisplayNumber(this.currentOperand) - 删除冗余全局变量
移除类外重复定义的两行DOM查询代码:// 删除以下两行冗余代码 // const previousOperand = document.querySelector('[data-previous-operand]') // const currentOperand = document.querySelector('[data-current-operand]')
内容的提问来源于stack exchange,提问作者HaloDonuts J
相关产品推荐
相关产品推荐

