如何使用ES6 super在子构造函数中调用父方法?

时间:2017-10-05 16:28:15

标签: javascript node.js ecmascript-6 super es6-class

情况:

我正在扩展Node.js(v.8.4.0)具有附加属性(timestamp,id)的错误对象,然后扩展此对象以获得更精细的错误处理。

class MyError extends Error {
  constructor (msg) {
    super(msg);
    this.id = uuid();
    this.timestamp = Date.now();
    // I reckon this can be replaced by this.init(this) ?
    this.name = this.constructor.name;
    Error.captureStackTrace && Error.captureStackTrace(this, this.constructor);
  }

  init (self) {
    self.name = self.constructor.name;
    Error.captureStackTrace && Error.captureStackTrace(self, self.constructor);
  }
}

我希望能够在子错误中不重复Error.captureStackTracethis.name次调用。所以我创建了一个我在子节点中使用的init函数:

class GranularError extends MyError {
  constructor (msg) {
    super(msg);
    this.type = "error";
    this.status = 500;
    this.code = "internalServerError";
    super.init(this);
  }
}

GranularError将再次延长以获得MoreGranularError等。这就是为什么我要保持干燥的原因。

问题:

当抛出GranularError或MoreGranularError时,它会以

失败
TypeError: (intermediate value).init is not a function

我主要阅读以下来源,但我还没有能够将它们应用到问题中。任何帮助表示赞赏。

Call parent function which is being overridden by child during constructor chain in JavaScript(ES6)

Parent constructor call overridden functions before all child constructors are finished

http://2ality.com/2015/02/es6-classes-final.html#referring_to_super-properties_in_methods

1 个答案:

答案 0 :(得分:2)

我不知道您收到此错误的内容,但无需创建init功能。 this.nameError.captureStack内容也适用于孩子,因为this引用了子实例。

换句话说,您正试图解决一个不存在的问题。



class MyError extends Error {
  constructor (msg) {
    super(msg);
    this.id = Math.random();
    this.timestamp = Date.now();
    this.name = this.constructor.name;
    Error.captureStackTrace && Error.captureStackTrace(this, this.constructor);
  }
}
class GranularError extends MyError {
  constructor (msg) {
    super(msg);
    this.type = "error";
    this.status = 500;
    this.code = "internalServerError";
  }
}

console.dir(new GranularError("this is the error message"));