wscourge wscourge - 1 month ago 13
Javascript Question

Save extending class' methods' names in constructor

I have three classes, two of them extending the third. Is it possible to somehow (different than manually) assign extending classes' names to the super constructor?

class Master {

constructor(options) {
this.methods = Object.getOwnPropertyNames( Master.prototype );
}

getMethods() {
return Object.getOwnPropertyNames( Master.prototype );
}

}

class SlaveOne extends Master {
constructor(options) {
super(options);
}
methodOne() {}
methodTwo() {}
}

class SlaveTwo extends Master {
constructor(options) {
super(options);
}
methodThree() {}
methodFour() {}
}


So, what I want is to have either method or
this.methods
assignment in the Master class, which will:


  • return
    ['constructor', 'methodOne', 'methodTwo']
    when called on an instance of
    SlaveOne
    ;

  • return
    ['constructor', 'methodThree', 'methodFour']
    when called on an instance of
    SlaveTwo
    ;



My current code will return same
['constructor', 'getMethods']
when called either on instance of
SlaveOne
,
SlaveTwo
or
Master
. Any ideas?

Answer Source

Something like this should do the trick

class Master {

    getMethods() {
        return Object.getOwnPropertyNames( this.constructor.prototype );
    }

}

class SlaveOne extends Master {
    constructor(options) {
        super(options);
    }
    methodOne() {}
    methodTwo() {}
}

class SlaveTwo extends Master {
    constructor(options) {
        super(options);
    }
    methodThree() {}
    methodFour() {}
}

console.log(new SlaveOne().getMethods(), new SlaveTwo().getMethods())