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

如何不使用Calculator构造器重写JavaScript计算器功能代码

无构造器计算器实现代码

采用工厂函数写法实现,完全移除class和constructor语法,原有所有功能逻辑无改动,仅调整代码结构:

// 计算器工厂函数,传入显示元素参数直接生成计算器实例
function createCalculator(previousOperandTextElement, currentOperandTextElement) {
  // 内部状态存储,替代原class的this属性
  let currentOperand = ''
  let previousOperand = ''
  let operation = undefined

  // 清空所有输入和运算状态
  function clear() {
    currentOperand = ''
    previousOperand = ''
    operation = undefined
  }

  // 删除当前输入的最后一位
  function deleteLast() {
    currentOperand = currentOperand.toString().slice(0, -1)
  }

  // 追加输入数字/小数点
  function appendNumber(number) {
    if (number === '.' && currentOperand.includes('.')) return
    currentOperand = currentOperand.toString() + number.toString()
  }

  // 选择运算符
  function chooseOperation(op) {
    if (currentOperand === '') return
    if (previousOperand !== '') {
      compute()
    }
    operation = op
    previousOperand = currentOperand
    currentOperand = ''
  }

  // 执行运算
  function compute() {
    let computation
    const prev = parseFloat(previousOperand)
    const current = parseFloat(currentOperand)
    if (isNaN(prev) || isNaN(current)) return
    switch (operation) {
      case '+':
        computation = prev + current
        break
      case '-':
        computation = prev - current
        break
      case '*':
        computation = prev * current
        break
      case '÷':
        computation = prev / current
        break
      default:
        return
    }
    currentOperand = computation
    operation = undefined
    previousOperand = ''
  }

  // 格式化显示数字(带千分位分隔)
  function getDisplayNumber(number) {
    const stringNumber = number.toString()
    const integerDigits = parseFloat(stringNumber.split('.')[0])
    const decimalDigits = stringNumber.split('.')[1]
    let integerDisplay
    if (isNaN(integerDigits)) {
      integerDisplay = ''
    } else {
      integerDisplay = integerDigits.toLocaleString('en', { maximumFractionDigits: 0 })
    }
    if (decimalDigits != null) {
      return `${integerDisplay}.${decimalDigits}`
    } else {
      return integerDisplay
    }
  }

  // 更新页面显示
  function updateDisplay() {
    currentOperandTextElement.innerText = getDisplayNumber(currentOperand)
    if (operation != null) {
      previousOperandTextElement.innerText = `${getDisplayNumber(previousOperand)} ${operation}`
    } else {
      previousOperandTextElement.innerText = ''
    }
  }

  // 初始化执行清空
  clear()

  // 暴露对外调用的方法
  return {
    clear,
    delete: deleteLast,
    appendNumber,
    chooseOperation,
    compute,
    updateDisplay
  }
}

调用方式调整

原来的实例化写法new Calculator(prevEl, currEl)直接替换为createCalculator(prevEl, currEl)即可,所有实例方法调用逻辑完全不需要改动。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:48:03