Ruší volání konstruktoru s ES6 proxy

Přišel jsem s ES6 Proxies a zeptal jsem se sám sebe, jak zasahovat do new volání. Jdeme na to!

// 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"

Není to jen get , set a new které lze zasahovat. Kompletní seznam najdete na MDN.