在新环境中使用 'super' 的最佳方式是什么?

What's the best way to use 'super' in a new context?

在 ES6 中使用 classes 时,'super' 关键字只能直接在 class 方法中使用。这是完全合理的,但有时会很尴尬。

这是我想出的解决方法,但还有更好的方法吗?

class foo {

  constructor () {
  }

  bar (x) {
    console.log('bar x:', x);
  }

}

class morefoo extends foo {

  constructor () {
    super();
  }
 
  bar (x) {
    let super_bar = super.bar.bind(this);
    setTimeout(function () {
      //super.bar(x*2); // => 'super' keyword unexpected here
      super_bar(x*2);
    }, 0); 
  }

}

let f = new morefoo;
f.bar(33);

如果您想在回调中引用 super,请使用 arrow function

class foo {

  constructor () {
  }

  bar (x) {
    console.log('bar x:', x);
  }

}

class morefoo extends foo {

  constructor () {
    super();
  }
 
  bar (x) {
    setTimeout(() => super.bar(x*2), 0); 
  }

}

let f = new morefoo;
f.bar(33);

箭头函数以不同方式处理某些 keywords/variables(thisargumentssuper)。