Intercept JavaScript constructor calls with ES6 Proxies
Written by Stefan Judis
- Published at
- Updated at
- Reading time
- 1min
This post is part of my Today I learned series in which I share all my web development learnings.
I came along ES6 Proxies and wondered how to intercept a new
call in JavaScript.
So, here we go!
// proxy handler
const handler = {
// let's intercept the `new` call
// log out which object was called with which arguments
construct : ( target, args ) => {
console.log( `Initializing ${ target.name } with:`, args );
return new target();
}
};
// -------------------
/**
* Intercept a called constructor function
*/
function ConstructorFunction() {
this.call = () => {
console.log( 'method call 1' );
};
}
const ProxiedConstructorFn = new Proxy( ConstructorFunction, handler );
const foo = new ProxiedConstructorFn( 'foo' );
// logs "Initializing ConstructorFunction", [ "foo" ]
foo.call();
// logs "method call 1"
// -------------------
/**
* Intercept a ECMAScript class constructor
*/
class ClassConstruct {
constructor() {}
call() {
console.log( 'method call 2' );
}
}
const ProxiedClass = new Proxy( ClassConstruct, handler );
const bar = new ProxiedClass( 'bar' );
// logs "Initializing ClassConstruct", [ "bar" ]
bar.call();
// logs "method call 2"
It's not only get
, set
and new
that can be intercepted. You can find a complete list on MDN.
If you enjoyed this article...
Join 5.6k readers and learn something new every week with Web Weekly.
Reply to this post and share your thoughts via good old email.