Faccion Faccion - 3 months ago 13
Javascript Question

super.method context handling in ES6

As there are no private method support yet in Javascript, I usually simply declare a normal function outside of class body and provide

this
as argument:

class Foo {
constructor() {
_doPrivateStuff(this);
}
}

function _doPrivateStuff(that) {
that.bar() // private stuff
}

export default Foo;


But how can I acess super.method in this way?

function _doPrivateStuff(that) {
super.method(); // error, 'super' outside of function or class
}


Besides that, is there a good reason why I should not be using 'private' functions like this?

Btw, I only tried this on Babel, and using
_doPrivateStuff.bind(this)()
instead of using
that
doesn't works either

Answer

super only works inside of a class itself because for super to work, the class needs to know Foo, so it can do (simplified) Object.getPrototypeOf(Foo).method.call(this) to call the parent class's method. When you just have a standalone function, there is no way for the class to know how to call super.

To do what you want, you'd have to do

class Foo {
    constructor() {
        _doPrivateStuff(this, () => super.bar());
    }
}

function _doPrivateStuff(that, superBar) {
    superBar();
}

To expand on that with a counterexample, what if your had an extra layer of classes:

class Base {
    method(){ console.log('base'); }
}
class Mid extends Base {
    method(){ console.log('mid'); }

    run(){ doPrivateThing(this); }
}

class Child extends Mid {}

new Child();

function doPrivateThing(that){
    // super.method();
}

If your example did work, you'd passed doPrivateThing an instance of Child, it has no way of knowing that it was called from inside Mid, should it log mid or base? There isn't enough information to know.

Comments