Synthesizing Members Directly on an Instance

Learn how to synthesize members directly on instances of a class instead of a proxy.

The two pillars

Rather than calling proxy.key, we should be able to perform anyInstanceOfMap.key. To achieve this, we need to bring two different pieces of knowledge together.

  1. First, when a nonexistent property is requested on an object, JavaScript automatically requests it from the object’s prototype. If the prototype does not have it, the search continues through the prototype chain—see Understanding Prototypal Inheritance.

  2. Second, a proxy can trap requests for properties, fields, and methods, among other things—in essence, the details we have explored in this chapter.

Combining the two pieces

Let’s combine these two pieces of knowledge to create a powerful synthesis.

  • If a property or a method exists, we simply want to use it; there is no need to mess with proxy or traps in this case.

📍Let the proxy step in only if a property or a method does not exist.

  • We know that JavaScript will look to an object’s prototype when something does not exist on an object; this is a good spot to synthesize. Thus, we can place the proxy behind an object as its prototype, instead of what we did in the previous lesson, to put the proxy in front of the object—ta-da!

Playing with prototypes

We almost have a solution, but we have to be careful when replacing prototypes. Let’s continue with the Map class, which we discussed in the previous lesson. An instance of Map gets its instance methods from its prototype—that is, Map.prototype. Replacing the Map instance’s prototype will, unfortunately, get rid of those methods—not a good idea. It turns out that Map.prototype’s prototype is an empty object; we can find this by calling:

console.log(Reflect.getPrototypeOf(Map.prototype));

That’s a good candidate to replace with a proxy.

Design of Map proxy

The design thought is illustrated in the prototype diagram given below.

Get hands-on with 1400+ tech skills courses.