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

情况:

我使用其他属性(timestamp,id)来扩展Node.js(v.8.4.0)Error对象,然后扩展这个对象以获得更精细的error handling。

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调用。 所以我创build了一个我在孩子中使用的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时,它会失败并返回a

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

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

调用JavaScript中的构造函数链中由子项覆盖的父函数(ES6)

父构造函数在所有子构造函数完成之前调用覆盖函数

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

我不知道你得到这个错误,但是不需要创build一个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"));