Last active
December 19, 2018 22:11
-
-
Save cantremember/97cc595df16ca732983fc8b01731798f to your computer and use it in GitHub Desktop.
using a Proxy to monkey-patch a method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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