3

It should be something like:

class C {
    static m() { console.log('hi') }
}

// automatically run C.m
class D extends C { }

A python case is found. Is this possible in JavaScript?

kakakali
  • 159
  • 1
  • 11
  • I don't think you can. but why do you want to do this? any use cases? – kennarddh Sep 02 '23 at 15:05
  • I think you can with custom transpiler like custom babel plugin. – kennarddh Sep 02 '23 at 15:08
  • 1
    It's not possible*, but what's the point anyway? Sounds like an [XY problem](https://xyproblem.info). Please explain what you want to achieve with this. --- *: Well, there may be one super quirky way, but I think therein lies madness: You could make the `prototype` property a getter or use a proxy that listens on get operations of the `prototype` property. The line `class D extends C {}` _does_ invoke a read operation on the property `C.prototype`. But the next challenge would be to differentiate this situation from other accesses of that property (e.g. during `new C()` or manualy access). – CherryDT Sep 02 '23 at 15:37

3 Answers3

4

Javascript doesn't have a metaclass per se, but you can create a pseudo metaclass by defining a class within a function:

function C() {
    class Cls {
      static m() { console.log('hi') }
    }
    Cls.m()
    return Cls
}

class D extends C() {} // prints 'hi'
Lord Elrond
  • 13,430
  • 7
  • 40
  • 80
0

In JS, you can't automatically run code when a subclass is declared.

bartekczrn
  • 59
  • 9
0

This can be solved using custom transpiler.

I have made a simple package to solve this problem.

class Y extends X {}

// This package will always add this after every class that extends other class
X?.onExtend(Y)

You can see the babel plugin implementation here

This package demo

kennarddh
  • 2,186
  • 2
  • 6
  • 21