bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/JavaScript/Objects, Classes, and Advanced Patterns
JavaScript•Objects, Classes, and Advanced Patterns

JavaScript Meta Programming

Concept visual

JavaScript Meta Programming

Pointer walk
two pointers
leftright102132436485116
left=0
right=6
1
3

Start at both ends

Metaprogramming

Metaprogramming refers to a number of ways a program can manipulate itself

Modify objects at runtime

Inspect objects at runtime

Control objects at runtime

Intercept running operations

Modify functions, and classes

Generate dynamic code

The Easy Explanation

Normally, code handles data. With metaprogramming, code handles code.

Inspecting Objects

With the method

Object.keys() you can inspect object properties.

Using

Object.keys() is a simple example of metaprogramming.

Example

This code is analyzing another piece of code (an object): // Create an Object const user = {name: "Jan", age: 40};

// Fill Array with Object keys const myArr = Object.keys(user);

Modify Objects

I typical metaprogramming task is to modify object behaviour

Example

// Create an Object const person = {name: "John", age: 41};

// Define "name" to return "secret"
Object.defineProperty(person, "name", {
get() { return "secret"; }
});
let name = person.name;

Generate Dynamic Code

Metaprogramming involves dynamic code generation. JavaScript can generate functions at runtime:

Example

const fn = new Function("a", "b", "return a + b");

Metaprogramming Examples

Consept

Description

Validation

Restrict the values that can be set to a property

Logging

Display property changes using a Proxy

Debugging

Intercept an operation using a Proxy

Frameworks

Vue, MobX, and Svelte use metaprogramming to detect state changes

Formula

ORM / database mapping

Wrap objects and creates fields based on database schema

Previous

JavaScript Dynamic Modules

Next

JavaScript Reflect