https://www.jianshu.com/p/bb066b93338b
将数据结构与数据操作分离,不同的访问者访问这个对象都会呈现出不同的处理方式
js实现
class DocumentReader {constructor(name) {this.name = name;}access(read) {console.log(this.name, " read:", read(this));}}// 前端开发class WebDevelopers extends DocumentReader {constructor(name) {super(name);}}// 测试人员class Tester extends DocumentReader {constructor(name) {super(name);}}const webDevelopers = new WebDevelopers("aaa");const tester = new Tester("bbb");function visitor(visitor) {if (visitor.constructor === WebDevelopers) {return {a: "11111",aa: "111111",};} else if (visitor.constructor === Tester) {return {b: "222222",};}}webDevelopers.access(visitor);tester.access(visitor);
可以理解为一种访问对象的策略模式
babel插件中的访问者
const MyVisitor = {Identifier() {console.log("Called!");}};
这是一个简单的访问者,把它用于遍历中时,每当在树中遇见一个 Identifier 的时候会调用 Identifier() 方法。
