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

能否将面向对象(OOP)的Clock转换为非实例化函数?

将Clock类改造为纯函数式实现

你可以用工厂函数替代原来的构造函数,不需要new实例化,同时保留每个时钟的独立状态,完全符合纯函数为主的项目风格。

改造后的代码

function createClock(checkInterval) {
  let offset;
  let clock;
  let interval;

  // 初始化状态
  reset();

  function start() {
    if (!interval) {
      offset = Date.now();
      interval = setInterval(update, checkInterval);
    }
  }

  function update() {
    clock += delta();
  }

  function delta() {
    const now = Date.now();
    const d = now - offset;
    offset = now;
    return d;
  }

  function stop() {
    if (interval) {
      clearInterval(interval);
      interval = null;
    }
  }

  function reset() {
    clock = 0;
  }

  function read() {
    return clock;
  }

  // 返回公共API
  return {
    start,
    stop,
    reset,
    read
  };
}

module.exports = createClock;

使用方式

调用工厂函数即可创建独立的时钟实例,无需new关键字:

const timer = createClock(1);
await timer.start();
const coolDownTimer = createClock(2);
const globalTimer = createClock(3);
await globalTimer.start();

核心说明

  • 每个createClock调用都会生成独立的私有状态(offset、clock、interval),和原OOP版本的实例完全隔离,互不干扰。
  • 逻辑和原构造函数完全一致,只是把绑定this的方式换成返回对象,规避了面向对象的实例化语法。
  • 保持状态封装,外部无法直接修改内部状态,保证了时钟行为的可控性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 14:35:26