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 asked myself how to interfere a new call. Here we go!

// proxy handler
const handler = {
  // let's interfere 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();
  }
};

/**
 * Interfere a 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"

/**
 * Interfere a 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 interfered. You can find a complete list on MDN.

Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 9 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles