https://www.jianshu.com/p/bb066b93338b

    将数据结构与数据操作分离,不同的访问者访问这个对象都会呈现出不同的处理方式

    js实现

    1. class DocumentReader {
    2. constructor(name) {
    3. this.name = name;
    4. }
    5. access(read) {
    6. console.log(this.name, " read:", read(this));
    7. }
    8. }
    9. // 前端开发
    10. class WebDevelopers extends DocumentReader {
    11. constructor(name) {
    12. super(name);
    13. }
    14. }
    15. // 测试人员
    16. class Tester extends DocumentReader {
    17. constructor(name) {
    18. super(name);
    19. }
    20. }
    21. const webDevelopers = new WebDevelopers("aaa");
    22. const tester = new Tester("bbb");
    23. function visitor(visitor) {
    24. if (visitor.constructor === WebDevelopers) {
    25. return {
    26. a: "11111",
    27. aa: "111111",
    28. };
    29. } else if (visitor.constructor === Tester) {
    30. return {
    31. b: "222222",
    32. };
    33. }
    34. }
    35. webDevelopers.access(visitor);
    36. tester.access(visitor);

    可以理解为一种访问对象的策略模式

    babel插件中的访问者

    1. const MyVisitor = {
    2. Identifier() {
    3. console.log("Called!");
    4. }
    5. };

    这是一个简单的访问者,把它用于遍历中时,每当在树中遇见一个 Identifier 的时候会调用 Identifier() 方法。

    https://zhuanlan.zhihu.com/p/333951676