Fac*_*ion 2 javascript this super ecmascript-6
由于Javascript中还没有私有方法支持,我通常只是在类体外声明一个普通函数并提供this参数:
class Foo {
constructor() {
_doPrivateStuff(this);
}
}
function _doPrivateStuff(that) {
that.bar() // private stuff
}
export default Foo;
Run Code Online (Sandbox Code Playgroud)
但是我怎么能以这种方式接受超级方法呢?
function _doPrivateStuff(that) {
super.method(); // error, 'super' outside of function or class
}
Run Code Online (Sandbox Code Playgroud)
除此之外,有一个很好的理由,为什么我不应该用这样的"私人"的功能呢?
顺便说一句,我只在Babel上试过这个,而使用_doPrivateStuff.bind(this)()而不是使用that也不起作用
super只能在类本身内部super工作,因为要工作,类需要知道Foo,所以它可以(简化)Object.getPrototypeOf(Foo).prototype.method.call(this)来调用父类method.当你只有一个独立的功能时,课程就无法知道如何打电话super.
要做你想做的事,你必须这样做
class Foo {
constructor() {
_doPrivateStuff(this, () => super.bar());
}
}
function _doPrivateStuff(that, superBar) {
superBar();
}
Run Code Online (Sandbox Code Playgroud)
要通过反例进行扩展,如果您有一个额外的类层,该怎么办?
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();
}
Run Code Online (Sandbox Code Playgroud)
如果您的示例确实有效,那么您已经传递doPrivateThing了一个实例Child,它无法知道它是从内部调用的Mid,如果它是日志mid还是base?没有足够的信息可以知道.
| 归档时间: |
|
| 查看次数: |
524 次 |
| 最近记录: |