1. (function () {
    2. class Sub {
    3. pond = []; //给实例设置的私有属性:this.pond=[]
    4. on(func) {
    5. let pond = this.pond;
    6. if (pond.includes(func)) return;
    7. pond.push(func);
    8. }
    9. off(func) {
    10. let pond = this.pond,
    11. i = 0,
    12. item;
    13. for (; i < pond.length; i++) {
    14. item = pond[i];
    15. if (item === func) {
    16. pond[i] = null;
    17. return;
    18. }
    19. }
    20. }
    21. fire(...params) {
    22. let pond = this.pond,
    23. i = 0,
    24. item;
    25. for (; i < pond.length; i++) {
    26. item = pond[i];
    27. if (typeof item === 'function') {
    28. item(...params);
    29. continue;
    30. }
    31. pond.splice(i, 1);
    32. i--;
    33. }
    34. }
    35. }
    36. /* 暴露API */
    37. if (typeof window !== 'undefined') window.Sub = Sub;
    38. if (typeof module === 'object' && typeof module.exports === 'object') module.exports = Sub;
    39. })();

    使用如下

    1. let sub1 = new Sub;
    2. setTimeout(() => {
    3. sub1.fire();
    4. }, 1000);
    5. let sub2 = new Sub;
    6. submit.onclick = function () {
    7. sub2.fire();
    8. };
    9. const fn1 = () => console.log(1);
    10. const fn2 = () => console.log(2);
    11. const fn3 = () => console.log(3);
    12. const fn4 = () => console.log(4);
    13. const fn5 = () => console.log(5);
    14. sub1.on(fn1);
    15. sub1.on(fn2);
    16. sub1.on(fn3);
    17. sub2.on(fn2);
    18. sub2.on(fn3);
    19. sub2.on(fn4);
    20. sub2.on(fn5);