<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> </body> <script> // 自定义事件; 把函数当成事件执行; function event1() { console.log("很多逻辑111"); //a写的; } function event2() { console.log("很很多逻辑222") //b写的; } class MyEvent { constructor() { this.handle = {}; } //添加自定义事件 addEvent(evnetName, fn) { if (typeof this.handle[evnetName] == "undefined") { this.handle[evnetName] = []; } this.handle[evnetName].push(fn); } // 触发自定义事件 trigger(evnetName) { this.handle[evnetName].forEach(v => { v(); }) } //移除自定义事件 removeEvent(eventName, fn) { if (!fn in this.handle[eventName]) { return; } for (let i = 0; i < this.handle[eventName].length; i++) { if (this.handle[eventName][i] === fn) { this.handle[eventName].splice(i, 1); break; } } } } let newEvent = new MyEvent(); newEvent.addEvent("myfn",event1); newEvent.addEvent("myfn",event2); newEvent.removeEvent("myfn",event2); newEvent.trigger("myfn"); </script> </html>