Search code examples
ecmascript-6metaprogramminges6-classes6-proxy

Trapping class definition via Proxy in ES6


Is it possible to trap extends? Or to trap definitions inside a class? Eg:

class B extends A {
    method1( ) { }
    static method2( ) { }
}


Is there any way to trap the events that:

  • B extended A.
  • method1( ) was defined on B.prototype
  • method2( ) was defined on B.


None of the existing mechanisms seem to work. Tried setPrototypeOf and defineProperty traps.


Solution

  • When class B extends class A, it gets its prototype object. So you can define a Proxy with a trap on get et check if the property being accessed is "prototype".

    class A {}
    
    PA = new Proxy(A, {
      get(target, property, receiver) {
        console.log('get', property)
        if (property == 'prototype')
          console.info('extending %o, prototype=%s', target, target.prototype)
        return target[property]
      }
    })
    
    class B extends PA {}