In Haxe (JS Target) is there a way to make static members available to another class as if it was its own?

109 Views Asked by At

I have this Haxe class that is growing quite large. It consists mostly of static methods & properties. (It's a module set to compile as JS target).

I would like to separate some of the complex static functions into another class.

Is there any way to mark it with a metatag / indicate the other class is an "extension" to the original class?

Something like @:native("OriginalClass") class OtherClass {...}

The goal is to avoid having to write the full variable access (ex: OriginalClass.LOG_QUEUE vs. LOG_QUEUE) or clutter the imports with each OriginalClass's static methods / properties used at the top of the OtherClass. Basically, something to make it aware that it "is" using the same members as the OriginalClass (whenever an 'undefined' one is found, at compile-time).

Example:

If OriginalClass has static var LOG_QUEUE:Array<String>; then OtherClass would be aware that any usage of LOG_QUEUE compiles to this JS code OriginalClass.LOG_QUEUE

1

There are 1 best solutions below

0
On

Alright, got a solution after discussing with Dima Granetchi from the Haxe experts group on Slack.

Now, although this will still generate the OtherClass that makes use of the OriginalClass's static members, you can cut down on the quantity of import statements for most (if not all) of the module/class's static members by using the wildcard * symbol, like in this example:

// OriginalClass.hx
package somePackage;

class OriginalClass {
    public static var LOG_QUEUE:Array<String>;

    public static function main() {
        LOG_QUEUE = [];

        OtherClass.doSomething();
    }

    public static function doSomethingOriginal() {
        LOG_QUEUE.push("World!");
    }
}


// OtherClass.hx
import somePackage.OriginalClass.*; // <-- Demonstrating the WILDCARD (*) symbol

class OtherClass {
    public static function doSomething() {
        LOG_QUEUE.push("Hello"); //Resolved to OriginalClass.LOG_QUEUE
        doSomethingOriginal(); //Resolved to OriginalClass.doSomethingOriginal()
    }
}

Although this is a minimal example, it becomes more useful when you have a few different dozen static members used in your OtherClass.

Note

TypeDefs defined in the OriginalClass used inside the OtherClass doesn't seem to get recognized/resolved (may be due to missing public accessor, but I was unable to set it on my typedefs). You can always import those specific TypeDefs with individual import statements, like so:

//Somewhere at the top of OtherClass.hx...
import somePackage.OriginalClass.MyTypeDef;