Skip to content

Instantly share code, notes, and snippets.

Jack Anderson jelkand

Block or report user

Report or block jelkand

Hide content and notifications from this user.

Learn more about blocking users

Contact Support about this user’s behavior.

Learn more about reporting abuse

Report abuse
View GitHub Profile
View attachProxyUsage.js
// 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
View attachProxy.js
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);
}
View reflectionFunctionCall.js
console.log(Reflect.get(obj, 'x'));
Reflect.set(obj, 'x', 2);
View gist:6875ba7dbb4fd3e4c07af5bc27ed38e6

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 Jul 9, 2019
Using Proxy to track changes to JS objects
View attachProxy.js
// 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
You can’t perform that action at this time.