什么是最好的使用方式' super'在新的背景下?

时间:2017-04-19 19:50:41

标签: javascript es6-class

在ES6中使用课程时,超级'关键字只能在类方法中直接使用。这是完全合理的,但有时很尴尬。

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



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);




1 个答案:

答案 0 :(得分:2)

如果您想在回调中引用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);




箭头功能区别对待某些关键字/变量(thisargumentssuper)。

相关问题