Skip to content

Instantly share code, notes, and snippets.

View jelkand's full-sized avatar

Jack Anderson jelkand

View GitHub Profile
// usage:
const obj = { foo: 'bar' };
const proxiedObj = attachProxy(obj);
proxiedObj.foo = 'baz';
/* output:
VM192:4 setting value of prop: foo to value: baz obj {foo: "bar"}
VM192:5 console.trace
set @ VM192:5
const attachProxy = (target) => {
const handler = {
set(obj, prop, value) {
console.log('setting value of prop:', prop, 'to value:', value, 'obj', obj);
console.trace();
return Reflect.set(...arguments);
}
};
return new Proxy(target, handler);
}
console.log(Reflect.get(obj, 'x'));
Reflect.set(obj, 'x', 2);
console.log(obj.x);
obj.x = 2;
obj.someMethod();

Metaprogramming with Reflect and Proxy in Javascript

Metaprogramming is a powerful tool in any language, and with the advent of ES6, there are even more options for metaprogramming in JavaScript now! ES6 added Reflect and Proxy to its repertoire of built-in objects, which allow for dynamic behavior in your code.

What is metaprogramming?

At its core, metaprogramming is simple—it just means programs that can write programs. Think of it as code that can change itself or other code while running.

As you could imagine, metaprogramming is very powerful, but also very dangerous.

Why would you use metaprogramming?

  1. Changing the behavior of code you don’t control—for example, adding logging, validation, or other utility code to a third party library.
@jelkand
jelkand / attachProxy.js
Last active October 11, 2022 22:10
Using Proxy to track changes to JS objects
// usage:
const obj = { foo: 'bar' };
const proxiedObj = attachProxy(obj);
proxiedObj.foo = 'baz';
/* output:
VM192:4 setting value of prop: foo to value: baz obj {foo: "bar"}
VM192:5 console.trace
set @ VM192:5