【问题标题】:Get class name in constructor在构造函数中获取类名
【发布时间】:2017-01-18 02:49:04
【问题描述】:
export class InvalidCredentialsError extends Error {
  constructor(msg) {
    super(msg);
    this.message = msg;
    this.name = 'InvalidCredentialsError';
  }
}

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

【问题讨论】:

  • 您在寻找this.constructor.name吗?
  • @CodingIntrigue this.constructor.name 返回“错误”。
  • 奇怪。这可能是子类化Error 的问题,因为我不明白为什么它不会返回当前的类名。

标签: ecmascript-6


【解决方案1】:

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

不带 Babel(在 Chrome 或其他支持 class 的浏览器上使用):

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');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    相关资源
    最近更新 更多