gpt4 book ai didi

ecmascript-6 - 在构造函数中获取类名

转载 作者:行者123 更新时间:2023-12-04 04:53:11 24 4
gpt4 key购买 nike

export class InvalidCredentialsError extends Error {
constructor(msg) {
super(msg);
this.message = msg;
this.name = 'InvalidCredentialsError';
}
}

正如你在上面看到的,我正在写 InvalidCredentialsError两次。有没有办法以某种方式获取构造函数方法中已有的类名并设置它?还是对象必须被实例化?

最佳答案

在具有原生 ES6 类支持的浏览器中,this.constructor.name将显示 InvalidCredentialsError .如果你用 Babel 编译代码,它会显示 错误 .

没有 Babel(在 Chrome 或其他支持类的浏览器上使用):

class InvalidCredentialsError extends Error {
constructor(msg) {
super(msg);
console.log(this.constructor.name);
this.message = msg;
this.name = 'InvalidCredentialsError';
}
}

const instance = new InvalidCredentialsError('message');


与巴别塔:

class InvalidCredentialsError extends Error {
constructor(msg) {
super(msg);
console.log(this.constructor.name);
this.message = msg;
this.name = 'InvalidCredentialsError';
}
}

const instance = new InvalidCredentialsError('message');

关于ecmascript-6 - 在构造函数中获取类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41698433/

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