Chapter 11
Exploring Metaprogramming

Metaprogramming is a way to extend a program at runtime—it’s the ability to write code that writes code. It’s one of the most complex and yet one of the newest and most powerful features of JavaScript. You may use metaprogramming to dynamically extend code where you feel fit.

JavaScript classes are open—that is, you can extend them without using inheritance, which means you’re not limited to using the facilities provided by the author of the class. You can add your own convenience methods and properties to classes so that the code may be easier and more fluent to use, to meet your own style or preferences. And you can add these behaviors dynamically at runtime, anytime.

Inheritance forces you to create a new class to extend the behavior of a class. Metaprogramming permits you to extend a class in place. That is, when you extend a class using inheritance, the added features are available only in the instance of the derived class and not in the instances of the base class. However, when you extend a class with metaprogramming you enhance an existing class without creating any additional classes.

Several JavaScript libraries and frameworks, like React and Angular, make extensive use of metaprogramming to pull metadata from code, to take special actions or implement special behaviors. Knowing metaprogramming greatly demystifies the code you write to use these libraries or frameworks. Furthermore, it helps you approach testing such code with greater confidence. Metaprogramming is like a smartphone; once you get hooked, you wonder how anyone survived without one.

Metaprogramming comes in two flavors: member injection and member synthesis. Injection, which we discuss in this chapter, is useful to add well-known methods to existing classes. Synthesis, which the next chapter dives into, is useful to dynamically create methods and properties based on the current state of objects.

Metaprogramming is quite powerful, but we have to be very careful when using it. In this chapter we’ll start with a short discussion of the capabilities of metaprogramming and the cautions we should take in using it. Then we’ll look at various techniques to inject members into existing classes.

Now is a good time to refill your favorite beverage—we’ve got some serious coding ahead of us.

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

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