3

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.

Gubbi
  • 756
  • 1
  • 7
  • 18
  • Where do you want to trap these thing? `B` doesn't exist at one moment and is already defined at another. Explaining your case would probably help. – Estus Flask Jan 15 '17 at 19:57
  • 1
    What problem are you really trying to solve by trapping extend? I'm guessing that there may be other ways to solve it that we could help with. – jfriend00 Jan 15 '17 at 20:29
  • Use cases are similar to why one would want to trap `defineProperty`: auto-run code when something is defined on an object. Since the `defineProperty` traps weren't triggered, I was checking if `extends` can be trapped. I don't have a strong use case for `extends` trapping otherwise. – Gubbi Jan 18 '17 at 04:30

1 Answers1

2

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 {}
Supersharp
  • 29,002
  • 9
  • 92
  • 134
  • 1
    @Gubbi note that the prototype could be accessed in other situations so be careful, maybe you'll need to check further depending on your use case. – Supersharp Apr 13 '17 at 15:56