Thi*_*ddi 1 javascript constructor class extend node.js
我在我的应用程序中创建了一些自定义 Erros,我想稍后使用构造函数名称检查它们。问题是当我在我的类中扩展 Error 时,constructor.name 总是“Error”,而不是我实际给它的名字。
我正在做一些测试,并注意到 Error 类会发生这种情况,但我创建的任何其他自定义类都不会发生这种情况。例如:
class CustomClass {
constructor(msg) {}
}
class OtherClass extends CustomClass {
constructor(msg) {
super(msg);
}
class CustomError extends Error {
constructor(msg) {
super(msg);
}
}
const e = new CustomError("There was an error");
const otherClass = new OtherClass("This is a class");
console.log(otherClass.constructor.name); // "OtherClass" <- ok!
console.log(e.constructor.name); // "Error" <- not ok! expected "CustomError"
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么会这样?
我以为我可以做这样的事情:
class CustomError extends Error {
constructor(msg) {
super(msg);
}
getName() {
return "CustomError";
}
}
const e = new CustomError("There was an error");
if(e.getName() == "CustomError") {
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
但后来我得到: TypeError: e.getName is not a function
编辑
按照@samanime 的建议,我将节点版本更新为 8.8.1,并找到了部分解决方案。
稍微改变一下我得到的语法:
const FileSystemException = module.exports = class FileSystemException extends Error {
constructor(msg) {
super(msg);
}
getName() {
return "FileSystemException";
}
}
const e = new FileSystemException("There was an error");
// Running node app.js
console.log(e.constructor.name); // "FileSystemException"
console.log(e.getName()); // "FileSystemException"
// Running babel-node app.js
console.log(e.constructor.name); // "Error"
console.log(e.getName()); // "TypeError: e.getName is not a function"
Run Code Online (Sandbox Code Playgroud)
尽管如此,如果有人能让它与 babel 一起工作,那将是很棒的,这样我就可以使用导入/导出语句而不必等待节点 v9.4 LTS。
使用:
节点 v8.8.1
babel-node v6.26.0 带有“es2015”和“stage-0”预设
谢谢!
在这个简单的例子中它似乎工作得很好:
class CustomError extends Error {
constructor(msg) {
super(msg);
}
}
const error = new CustomError()
console.log(error.constructor.name);
console.log(error instanceof CustomError);
console.log(error instanceof Error);Run Code Online (Sandbox Code Playgroud)
那是用本机运行的 class支持下(在 Chrome 中)。
这可能不是您的语法问题,而是您的转译器的问题。您可能想深入了解转译后的代码本身,看看它是否有什么特别之处Error与普通类不同的。
您的getName()示例不起作用的事实似乎也表明正在发生一些时髦的事情。您发布的示例看起来不错。仔细检查您尝试运行的代码实际上与它们匹配。
| 归档时间: |
|
| 查看次数: |
2741 次 |
| 最近记录: |