Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient and elegant way to create nested ES6 classes?

While trying to find a way to use nested classes in JS, I came up with this sort of thing:

class Character {
    constructor() {
        this.Info= class I {
            constructor(name,value) {
                this.name=name;
                this.value=value;   
            }
        };
    }
    bar () {
        var trial = new this.Info("Goofy", 2);
        alert(trial.name);
    }
}

var test = new Character();
test.bar();

and it seems to work. However, I'm afraid this might be creating a new function object for each new call, as I define the class in the constructor (which is executed at each new call). Is there a more efficient way of doing this?

This question does not solve my issue as the author only wonders how to even have a nested class; I'm already able to do that but I wonder if there's a more efficient way.

like image 970
memememe Avatar asked Nov 22 '25 10:11

memememe


1 Answers

Using a static property in react, angular or just using babel, because direct static class properties are not currently implemented on all browsers.

class Character {

    static Info = class I {
        constructor(name) { this.name=name; }
    }

    bar () {
        return new Character.Info("Goofy");
    }
}

const test = new Character();
console.log(test.bar());

Using a static property the old way -- currently working on all browsers.

class Character {
    bar () { return new Character.Info("Goofy"); }
}

Character.Info = class I {
    constructor(name) { this.name=name; }
}

const test = new Character();
console.log(test.bar());
like image 113
filipe Avatar answered Nov 24 '25 01:11

filipe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!