SlumTheSlug
SlumTheSlug

Reputation: 157

Access class inside function

I have a ready() function which contain an es6 class. I would like to instantiate this class outside the function, however I didn't succeed in making this working.

I don't want to use return function because the function can have more than one class.

Here is an example of what i want to do :

function ready(api) {
    class A extends api.C {
        contructor() {
            this.foo = "bar";
        }
    }

    class B extends A {
        contructor() {
            this.bar = "foo";
        }
    }
}

let classA = ready.A; // Here is the problem : I would like to access to the class prototype

The reason is my application have some plugins using remi npm package, and I want to export classes shared between all plugins. I don't know if it's possible, anybody have an idea ?

[EDIT] :

First thanks all for your hep, In fact I need to be more accurate in my issue. That's true, I can return back both classes through a classic return. But let me explain what I want to do exactly :

Here is how I describe a plugin :

/**
 * This class is a sample plugin
 * @class
 */
class Sample {
    constructor(api) {
        this.api = api;
    }


    /**
     * Shows a test log
     */
    test() {
        console.log("======> I'm working !");
    }
}

function loaded(api) {
    let s = new Sample(api);
}

module.exports = (api, options) => {

};

module.exports.attributes = {
    loadedCallback: loaded,
    name: "sample-plugin",
    version: "0.0.0",
    category: "misc",
    description: "I'm a sample plugin",
    classes: [Sample]
};

The core plugin manager will load the first time all plugins, and will register into an array all classes protoypes exported into the classes attributes property. Then the loaded(api) function is called and classes can be instantiated through api.classes object. In another plugin, I can do this :

function loaded(api) {
    let sample = new api.classes.Sample(api);   
}

And I can instantiate a class described in another plugin. That's the idea. However I would like to do a more complex API usage with the multiple inheritance, for example :

To be more clear, I would like to export globally some classes, to get a shared access between NPM modules

Upvotes: 0

Views: 1480

Answers (1)

ponury-kostek
ponury-kostek

Reputation: 8060

You can return class A from ready function, so after calling ready you can access A class

function ready(api) {
    class A extends api.C {
        contructor() {
            this.foo = "bar";
        }
    }

    class B extends A {
        contructor() {
            this.bar = "foo";
        }
    }
    return {A : A};
}

let classA = ready(api).A;

Upvotes: 1

Related Questions