登录
首页 >  文章 >  前端

JavaScript状态机实现全攻略

时间:2025-10-03 11:57:48 475浏览 收藏

编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《用JavaScript实现状态机的完整教程》,文章讲解的知识点主要包括,如果你对文章方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。

答案:使用ES6类、Map和异步方法实现状态机,支持状态转换校验与钩子函数。通过定义初始状态、允许的转移路径及事件触发规则,结合constructor初始化配置,can方法校验转换合法性,handle方法执行带前后钩子的异步状态变更,适用于订单等流程控制场景,代码清晰可扩展。

如何用现代JavaScript实现一个状态机(State Machine)?

用现代JavaScript实现一个状态机,关键在于明确状态、事件和状态转移规则。你可以利用ES6+的语法特性,如类(class)、Map结构和方法封装,让状态机清晰、可维护且易于扩展。

定义状态机的基本结构

一个状态机包含当前状态、允许的状态列表、触发状态变化的事件,以及每个状态下允许的转换规则。使用class来组织逻辑,可以提升代码的可读性和复用性。

下面是一个基础的State Machine类:

class StateMachine {
  constructor(config) {
    this.currentState = config.initial;
    this.states = config.states; // 如 { idle: ['loading'], loading: ['success', 'error'] }
    this.transitions = new Map();

    // 构建 transitions 映射:事件 => 状态对
    Object.keys(config.states).forEach(state => {
      config.states[state].forEach(event => {
        this.transitions.set(event, { from: state, to: event });
      });
    });
  }

  can(event) {
    const transition = Array.from(this.transitions.values()).find(t => t.from === this.currentState && t.to === event);
    return !!transition;
  }

  handle(event) {
    if (this.can(event)) {
      this.currentState = event;
      return true;
    }
    throw new Error(`Invalid transition: ${this.currentState} → ${event}`);
  }

  getCurrentState() {
    return this.currentState;
  }
}

使用示例:模拟订单流程

假设你有一个订单系统,状态包括“待支付”、“已支付”、“发货中”、“已完成”。可以用如下方式配置状态机:

const orderMachine = new StateMachine({
  initial: 'pending',
  states: {
    pending: ['paid'],
    paid: ['shipped'],
    shipped: ['delivered'],
    delivered: []
  }
});

console.log(orderMachine.getCurrentState()); // "pending"
orderMachine.handle('paid');
console.log(orderMachine.getCurrentState()); // "paid"
orderMachine.handle('shipped');
console.log(orderMachine.getCurrentState()); // "shipped"

增强功能:添加钩子和异步支持

实际项目中,状态切换可能需要执行副作用,比如发送请求或更新UI。可以在转换前后加入钩子函数。

改进handle方法:

async handle(event, ...args) {
  const transition = Array.from(this.transitions.values()).find(
    t => t.from === this.currentState && t.to === event
  );

  if (!transition) {
    throw new Error(`Invalid transition: ${this.currentState} → ${event}`);
  }

  const beforeKey = `before${event.charAt(0).toUpperCase() + event.slice(1)}`;
  const afterKey = `after${event.charAt(0).toUpperCase() + event.slice(1)}`;

  if (this[beforеKey] && typeof this[beforеKey] === 'function') {
    await this[beforеKey](...args);
  }

  this.currentState = event;

  if (this[аfterKey] && typeof this[аfterKey] === 'function') {
    await this[аfterKey](...args);
  }

  return true;
}

这样你就可以在子类中定义beforePaid、afterShipped等方法处理业务逻辑。

使用现代JS特性优化

利用Proxy可以拦截状态访问,用Symbol保护内部状态,或结合Promise支持异步流转。也可以导出为模块,在多个组件间共享状态逻辑。

基本上就这些——一个轻量、灵活、基于现代JavaScript的状态机就这样实现了。

今天关于《JavaScript状态机实现全攻略》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于JavaScript,状态机,异步,状态转换,ES6类的内容请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>