Javascript 如何使用ES6 super在子构造函数中调用父方法? 情况:
我用附加属性(timestamp,id)扩展Node.js(v.8.4.0)Error对象,然后扩展这个对象以获得更精确的错误处理Javascript 如何使用ES6 super在子构造函数中调用父方法? 情况:,javascript,node.js,ecmascript-6,super,es6-class,Javascript,Node.js,Ecmascript 6,Super,Es6 Class,我用附加属性(timestamp,id)扩展Node.js(v.8.4.0)Error对象,然后扩展这个对象以获得更精确的错误处理 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) ?
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);
}
}
我不希望重复错误。captureStackTrace
和this.name
调用子错误。因此,我创建了一个init函数,在子函数中使用:
class GranularError extends MyError {
constructor (msg) {
super(msg);
this.type = "error";
this.status = 500;
this.code = "internalServerError";
super.init(this);
}
}
GranularError
将再次扩展以获得更多GranularError
等。这就是我希望保持干燥的原因
问题:
当抛出GranularError或MoreGranularError时,它会失败,并出现错误
TypeError: (intermediate value).init is not a function
我主要阅读了以下资料来源,但还没有将它们应用到这个问题上。感谢您的帮助
我不知道您会遇到什么错误,但不需要创建
init
函数。this.name
和Error.captureStack
的东西也会在子实例中工作,因为this
引用子实例
换句话说,你在试图解决一个根本不存在的问题
类MyError扩展错误{
构造器(msg){
超级(味精);
this.id=Math.random();
this.timestamp=Date.now();
this.name=this.constructor.name;
Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor);
}
}
类GranularError扩展了MyError{
构造器(msg){
超级(味精);
this.type=“error”;
该状态=500;
this.code=“internalServerError”;
}
}
dir(新GranularError(“这是错误消息”)代码>您的代码在Chrome()中运行顺畅。您使用的是什么环境?(我猜是Node,基于uuid
?什么版本?)是的,是Node 8.4.0。我把它添加到开头。谢谢你的评论。它在Chrome上运行得很好,这确实很奇怪。在我尝试实现init函数之前,代码就是这样的。我一定是在其他地方出错了,在尝试实现init()时,我一定已经修复了它。现在可以了。谢谢。或者更好,用new.target
@Bergi替换this.constructor
。@Bergi在上面的上下文中使用new.target有实际的好处吗?还是它只是块上最酷的新手?@OndraUrban我猜:-)它甚至在super()
调用之前就工作了(因为它不使用this
),而且没有人能搞乱.constructor
属性(尽管与以前相比,类
语法的问题要少一些)。