Pseudo-classical Pattern

Thus far we haven’t really explored prototypal delegation other than to mention briefly that it exists. Now it’s time to see it in action and eliminate some code redundancy at the same time. Object prototypes and their delegation behavior are worthy of an entire blog post, but we can get at least a basic picture here. In essence, when a certain property is called on a certain object, for example someRobot.introduce() , it goes to look for that property first on itself. If no such property exists, it then looks at the properties available to its prototype object, which in turn looks at its prototype object if necessary, and so on all the way up to the top-level Object.prototype . The prototype chain allows delegation of behavior, wherein we don’t have to define some shared method on lower-level objects of the same type. Instead, we can define the behavior on whichever prototype they all share and thus eliminate redundancy by only defining the code once. Here it is in action with our robots.

As in the constructor pattern we are using the new keyword to create a new object, assign some state, and then implicitly return that object. However, in this case we do not define the introduce() method on each of our robots. Rather, we define it on the Robot.prototype object, which as we have seen, acts as the prototype of each new object created by the Robot constructor function. When we attempt to call, for example, wallE.introduce() , the wallE object sees that it has no such method and goes searching up its prototype chain, quickly finding a method by that name on Robot.prototype . Indeed, if we check wallE ’s prototype by using Object.getPrototypeOf() , we can see that it is indeed Robot.prototype .

This design pattern, known as the pseudo-classical pattern, solves both of the problems we initially saw in the factory pattern; however, it still presents us with the somewhat uncomfortable illusion of a class-based system. This can lead to some unfortunate detours in our mental model of how JavaScript really operates, and some unexpected gotchas in actual program execution. One solution to this problem, popularized by Kyle Simpson, author of You Don’t Know JS, is the Object Linked to Other Object (OLOO) Pattern, which we shall explore next.