You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS报错Uncaught SyntaxError:calculator标识符已声明如何修复

原生JS计算器重复声明报错排查

报错原因

控制台抛出Uncaught SyntaxError: Identifier 'calculator' has already been declared的核心原因是同作用域下标识符重名:

  • 你首先通过class calculator声明了一个类,类声明会在当前作用域绑定名为calculator的标识符
  • 后续实例化时你又通过const calculator声明了同名变量,JS引擎校验时发现标识符重复,直接抛出语法错误

JS中类声明和let/const声明遵循相同的作用域规则,同作用域内不允许重复声明同名标识符,类名本身也会占用变量名名额。

修复方法

按照JS通用命名规范,将类名改为大驼峰格式,和实例变量名做区分即可,修改后可直接运行的完整代码如下:

class Calculator {
  constructor(previousOperandTextElement, currentOperandTextElement) {
    this.previousOperandTextElement = previousOperandTextElement
    this.currentOperandTextElement = currentOperandTextElement
    this.clear()
  }
    
  clear() {
    this.currentOperand = ''
    this.previousOperand = ''
    this.operation = undefined
  }
    
  delete() {
  }

  appendNumber(number) {
    this.currentOperand = number
  }
    
  chooseOperation(operation) {   
  }
    
  compute() {
  }

  updateDisplay() {
    this.currentOperandTextElement.innerText = this.currentOperand;
  }
}
    
const numberButtons = document.querySelectorAll('[data-number]')
const operationButtons = document.querySelectorAll('[data-operation]')
const equalsButton = document.querySelector('[data-equals]')
const deleteButton = document.querySelector('[data-delete]')
const allclearButton = document.querySelector('[data-all-clear]')
const previousOperandTextElement = document.querySelector('[data-previous-operand]')
const currentOperandTextElement = document.querySelector('[data-current-operand]')
        
const calculator = new Calculator(previousOperandTextElement, currentOperandTextElement)

numberButtons.forEach(button => {
  button.addEventListener('click', () => {
    calculator.appendNumber(button.innerText)
    calculator.updateDisplay()
  })
})

待修正的潜在问题

你当前代码还有两个会影响后续功能的小问题,可提前调整:

  • 构造函数内属性拼写错误:原代码写的是this.perviousOperandTextElement,正确拼写为this.previousOperandTextElement,否则后续渲染历史操作数时会报属性不存在错误
  • appendNumber方法当前逻辑是直接覆盖当前操作数,点击多个数字时只会显示最后一次点击的值,正常追加逻辑应为:
appendNumber(number) {
  this.currentOperand = `${this.currentOperand}${number}`
}

内容的提问来源于stack exchange,提问作者Williams

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 16:42:58