在ES6中扩展类时,是否可以定义回调

fac*_*com 5 javascript ecmascript-6

基本上,如果调用我的库类,我想做一些设置工作.例如:

class Child extends Parent { 
    //methods
}
Run Code Online (Sandbox Code Playgroud)

我想在扩展Parent类时分配一个要调用的函数.我想以某种方式得到通知.在它即将发生之前(将要附加的方法作为参数),或者在将Child类作为参数之后.

我有一个我构建的ES5库,它使用工厂函数来创建新类,在该函数中我做了很多设置工作.我想做所有相同的东西,但ES6类语法的简单性,所以使用我的库的开发人员不需要考虑任何特殊的东西,并可以考虑更简单的类.

任何帮助将非常感激.

Vic*_*ves -1

您可以在 ES6 构造函数中将回调定义为:

class Point {
  constructor(x, y, cb) {
    this.x = x;
    this.y = y;
    if (typeof cb === 'function')  return cb();  //If Callback function is available, execute it
  }
}

class ColorPoint extends Point {
  constructor(x, y, color, cb) {
    super(x, y, cb);  //Pass callback to parent constructor
    this.color = color;
  }
}

let cp = new ColorPoint(25, 8, 'green', function () {
  alert('callback called')
});  //Callback function passed
Run Code Online (Sandbox Code Playgroud)

在这里小提琴