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?

6
  • I don't think you can. but why do you want to do this? any use cases? Commented Sep 2, 2023 at 15:05
  • I think you can with custom transpiler like custom babel plugin. Commented Sep 2, 2023 at 15:08
  • 2
    It's not possible*, but what's the point anyway? Sounds like an XY problem. 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). Commented Sep 2, 2023 at 15:37
  • stackoverflow.com/questions/44355812/… Commented Sep 3, 2023 at 6:53
  • 1
    @kennarddh The answer is wrong, but the question is the same Commented Sep 3, 2023 at 9:22

3 Answers 3

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' 
Sign up to request clarification or add additional context in comments.

5 Comments

Looks weird and not clean.
@kennarddh I agree, but that's as close as you can get to a metaclass as far as I'm aware
@kennarddh true, but I don't believe a much cleaner method would be possible.
A cleaner method is you need to create your own babel transpiler to transpile the source code to transpiled code and add extendedClass.onExtend() after the class definition.
@kennarddh I haven't written in Javascript in years, so I'm not familiar with babel. That seems like it would make for a good answer.
0

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

Comments

0

This can be solved using custom transpiler.

I have made a babel plugin library 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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.