super.method ES6 中的上下文处理

super.method context handling in ES6

由于 Javascript 中还没有私有方法支持,我通常只是在 class 主体之外声明一个普通函数并提供 this 作为参数:

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

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

export default Foo;

但是我怎样才能通过这种方式访问​​ super.method?

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

除此之外,有什么 为什么我不应该使用这样的 'private' 函数的原因吗?

顺便说一句,我只在 Babel 上尝试过,使用 _doPrivateStuff.bind(this)() 而不是 that 也不起作用

super 只能在 class 内部工作,因为要使 super 工作,class 需要知道 Foo,所以它可以(简化)Object.getPrototypeOf(Foo).prototype.method.call(this) 调用父 class 的 method。当您只有一个独立函数时,class 无法知道如何调用 super.

想做就得做

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

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

用一个反例来扩展它,如果你有一个额外的层 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();
}

如果您的示例确实有效,您已经传递了 doPrivateThing 一个 Child 的实例,它无法知道它是从 Mid 内部调用的,它应该记录mid 还是 base?没有足够的信息可以知道。