在构造函数中获取类名

Kar*_*son 5 ecmascript-6

export class InvalidCredentialsError extends Error {
  constructor(msg) {
    super(msg);
    this.message = msg;
    this.name = 'InvalidCredentialsError';
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Ori*_*ori 7

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

没有 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');
Run Code Online (Sandbox Code Playgroud)

与巴别塔:

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

const instance = new InvalidCredentialsError('message');
Run Code Online (Sandbox Code Playgroud)