chapter seven

7 Hooked on metaprogramming

 

This chapter covers

  • Using metaprogramming and reflection to hook into the runtime structure of your code and apply cross-functional behavior
  • Using symbols to create interoperability between different realms in your application
  • Augmenting JavaScript’s internals with well-known symbols like @@iterator
  • The basics of the Proxy/Reflect APIs
  • Emulating Aspect-Oriented Programming pointcuts with proxies

A program's text is just one representation of the program. Programs are not text... We need a different way to store and work with our programs.

Sergey Dmitriev, President and Co-founder of JetBrains

Imagine a company like Intel who build CPU chips. To automate a lot of the repetitive tasks, they program robots to build chips—this is programming. Then to scale to higher industry demands, they program factories, that build robots, that build chips—this is metaprogramming.

I hope by now you’re hooked on JavaScript—I know I am. Throughout our journey, we’ve been uncovering interesting similes. One of these is “functions as data” (chapter 4), or the idea of expressing an eventual value as an execution of some function. Taking this another level we have “modules as data” (chapter 6). This refers to JavaScript’s nature of reifying a module as a bound object.

7.1   Common uses of metaprogramming in JavaScript

7.2   JavaScript Symbols

7.3   Symbol registries

7.3.1   Local registry

7.3.2   Global registry

7.4   Practical application of symbols

7.4.1   Control switches

7.4.2   Serialization

7.5   Well-known symbols

7.5.1   @@toStringTag

7.5.2   @@isConcatSpreadable

7.5.3   @@species

Information hiding

Document closure of operations

7.5.4   @@toPrimitive

7.5.5   @@iterator

7.6   Dynamic introspection and weaving

7.6.1   Proxy objects

7.6.2   The Reflect API

7.6.3   Additional use cases

Auto-hashed blocks

measuring performance with revocable proxies

7.7   Emulating Aspect-Oriented Programming

7.8   Summary