The visitor pattern allows you to separate functionality
from the object it functions on. We can often make use of this pattern when working with
components and composites.
For instance, here’s a simple visitor used to console out the various property values nested
inside an object:
A visitor can also modify object values. In this meta example, I will use a createVisitor method
(which is a visitor) to modify a namespaced group of functions–making each a visitor.
If you run the above code in console, you may notice that while visitor.caps reports the obj
strings in all caps, it does not modify the strings in place.
Out visit method can only modify object values, not the values themselves. But it
sounds like something worth doing.
Below, I modified the visit method to take an additional parameter for the property. Our
visitor functions will have access to this (the parent object), the value (in the same
position as before in case they don’t need to modify values), and the property name. The
property name will allow us to modify the value in place using this[prop] notation.
Try it out; run the logger before and after running makeCaps: