Skip to content Skip to sidebar Skip to footer

Es 6 Dynamically Work On Class After Definition

I was previously rolling my own Javascript OOP but now I'm playing with ES6 and want to use the class defined after definition in a generic way. Note Any answer with new in it is n

Solution 1:

There is no javascript built-in trigger that is calling a method on a class when a subclass is defined that extends from it.

Because you're rolling your own library, you could craft some kind of method the creates and returns a new class that extends a given base class. Maybe check out this answer that may help how to define your classes: Instantiate a JavaScript Object Using a String to Define the Class Name

You could also check how other javascript libraries creates (sub)classes. For example, Ext JS has a ClassManager that you could look into.

When this question would be about instantiation and not about defining classes, I would say:

afterDefined(cls) {
    console.log(`Class name ${this.constructor.name}`);
}

Usage:

let x = new FromBase()
x.afterDefined() // --> Class name FromBase

To get the name of the class, use

staticafterDefined(cls) {
    console.log(`Class name ${this.name}`);
}

Solution 2:

Is this what you're looking for?

classBase {
    constructor(arg) { this.arg = arg; }

    staticafterDefined(cls) {
        console.log(`Class name ${this.constructor.name}`);
    }
}

Base = newProxy(Base, {
    get: function(target, key, receiver) {
        if (typeof target == 'function' && key == 'prototype' && target.name == Base.name) {
            Reflect.apply(Base.afterDefined, Reflect.construct(classFromBase {}, []), [])
        }
        return target[key];
    }
});

classFromBaseextendsBase {}

In order for this to load class names, you will have to embed or forward-declare that information inside of the Proxy receiverprior to extending from it (which means you either need to enumerate ahead of time which classes you'll be inheriting to or to have some function call just prior to that class's declaration).

There are a bunch of other neat total hacks in the same vein such as looking at the source (text) of the file that you just loaded JavaScript from and then parsing that text as if it were JavaScript (people have used this to write Scheme interpreters that can accept new code inside of <script> tags).

If you are a library author intending to target Node, there are even more ways to go about doing this.

Solution 3:

// base.jsclassBase {
constructor(arg) {
    this.arg = arg;
}

// This is the behaviour I'm afterafterDefined(cls) {
        console.log(`Class name ${cls}`);
    }
}


// frombase.jsclassFromBaseextendsBase {
    constructor(arg) {
        super(arg)
    }
}


let f = newFromBase();
f.afterDefined('text');//this you text or object

have to be aware of is. file loading order, super is an instance of the parent class. good luck.

Post a Comment for "Es 6 Dynamically Work On Class After Definition"