gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:00:37 25 4
gpt4 key购买 nike

情况:

我正在扩展 Node.js (v. 8.4.0) 带有附加属性(时间戳、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。所以我创建了一个我在 child 中使用的初始化函数:

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

最佳答案

我不知道你得到这个错误是什么,但没有必要创建一个 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"));

关于javascript - 如何使用 ES6 super 在子构造函数中调用父方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46590566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com