Chapter 12
Deep Dive into Metaprogramming

Method synthesis is the most powerful form of metaprogramming. You can alter the API and the behavior of objects based on the runtime context and state of the objects. You can take existing classes and twist and turn them, the way it make sense to meet your needs, far beyond what was intended by the author of a class.

Method synthesis was not possible until very recently in JavaScript. All you could do in the past was method injection, which you saw in the previous chapter. With the introduction of method synthesis and two new classes—Reflect and Proxy—you can intercept method invocations right in the middle of their execution and change the fate of the calls, the way you like.

With the ability to synthesize members at runtime, different objects of a class may entertain different methods and behavior. While this is highly complex programming, it provides phenomenal flexibility to alter the behavior of objects, and it makes the code incredibly extensible.

The Reflect class is a gateway interface to query for and access properties, methods, and metadata of objects. Whenever you want to get some details about an object’s metadata—for example, access the prototype of an object—Reflect is your go-to interface for such operations.

Proxy is the ninja of metaprogramming. It can wrap around objects and serve as an interceptor. You can configure a proxy to simply route a call to the actual method of the wrapped object or to an alternative implementation that you choose dynamically at runtime. This way, you can selectively alter the behavior of existing classes, without physically changing their source code.

While Proxy is the way to synthesize your own custom behavior, the state-of-the-art decorator is the way to synthesize predefined behaviors. In other words, to cook up your own dynamic methods, use Proxy. To inject a recipe of methods, created by a third party, use decorators. Although decorators are not currently supported natively by JavaScript runtimes, we’ll see how to make use of them with transpilers.

Take a deep breath; you’re about to dive into one of the most exhilarating capabilities of JavaScript. By far, I’d say, this is the most exciting part of both the language and this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.198.129