Metaprogramming
in ES6

Kalil de Lima - 2019

kalil.de.lima@fing.edu.uy

kalil@rootstrap.com

What is metaprogramming?

"Metaprogramming is a programming technique in which computer programs have the ability to treat other programs as their data. It means that a program can be designed to read, generate, analyze or transform other programs, and even modify itself while running."

Wikipedia

Why is useful?

  • Allows the programmer to automate error prone or repetitive tasks.
  • Sometimes the final details of the code are not yet decided (like the Rails "find_by_" methods)
  • Reduces the size of the codebase

Where is useful?

  • Frameworks
  • Templates
  • Generic methods
  • Parsers
  • Compilers

Symbols

Symbols allow our objects

to implement common interfaces such as making

one of our classes iterable by implementing the iterator symbol, so it can be used in a for (... of ...) loop.

Reflection

Reflection allows us to interact with any object trough a generic API

This allows us to operate with foreign (to our implementation) objects, setting some common ground in how to treat them.

We're going to see two approaches

What can we do with Symbols?

Symbols allow us to define unique identifiers,

for that reason they're ideal to implement our own version of common protocols like

  • iterator
  • toStringTag
  • toPrimitive

What can we do with Reflection?

Reflection allows us to treat any object under a common interface, this allows us to do things like

 

  • Operate with objects getting meaningful feedback for our operations
  • Write proxy and handler functions for our classes
  • Introspect information and act in consequence

What can we do with this tools?

  • Symbols can be extremely useful when you need to avoid namespace collisions in your project.
  • Well known symbols like iterator and toString allow us to modify some default behavior of your objects in case you need to.
  • The Reflect API unifies a lot of functions that are useful for inferring properties of your objects under a common namespace
  • The Reflect API also simplifies some code, like applying variadic functions over foreign objects.

 

Thanks for listening!

The code used is available at

  • https://www.github.com/kaozdl/js-meetup-talk

The slides are available at

  • https://www.slides.com/kalildelima/metaprogramming-es6

For further reading on the subject

  • https://www.keithcirkel.co.uk/metaprogramming-in-es6-symbols
  • http://qnimate.com/es6-reflect-api-tutorial/
  • https://ponyfoo.com/articles/es6-reflection-in-depth

Metaprogramming in ES6

By Kalil De Lima

Metaprogramming in ES6

  • 306