Skip to content

Instantly share code, notes, and snippets.

@cantremember
Last active December 19, 2018 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cantremember/97cc595df16ca732983fc8b01731798f to your computer and use it in GitHub Desktop.
Save cantremember/97cc595df16ca732983fc8b01731798f to your computer and use it in GitHub Desktop.
using a Proxy to monkey-patch a method
class Foo {
method() {
return 'foo';
}
}
class Wrapper {
constructor(wrapped) {
this.latch = 2; // arbitrary condition; "proxy it this many times"
return new Proxy(wrapped, this);
}
get(target, key, proxy) {
const actual = Reflect.get(target, key, proxy);
if ((key === 'method') && (this.latch !== 0)) {
return (...args) => {
return `${ Reflect.apply(actual, target, args) } @ ${ this.latch-- }`;
};
}
return actual;
}
}
const wrapped = new Wrapper(new Foo());
for (let i = 0; i < 5; ++i) {
console.log(i, wrapped.method());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment