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

用现代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;
}
}
假设你有一个订单系统,状态包括“待支付”、“已支付”、“发货中”、“已完成”。可以用如下方式配置状态机:
立即学习“Java免费学习笔记(深入)”;
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等方法处理业务逻辑。
利用Proxy可以拦截状态访问,用Symbol保护内部状态,或结合Promise支持异步流转。也可以导出为模块,在多个组件间共享状态逻辑。
基本上就这些——一个轻量、灵活、基于现代JavaScript的状态机就这样实现了。
以上就是如何用现代JavaScript实现一个状态机(State Machine)?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号