instanceof自定义错误类返回false

时间:2017-01-18 12:15:05

标签: javascript

为什么会导致错误?

'use strict';

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

const err = new InvalidCredentialsError('');

console.log(err instanceof InvalidCredentialsError);

但这会返回true:

console.log(err instanceof Error);

enter image description here

1 个答案:

答案 0 :(得分:3)

这有效......您需要构建类型的实例,然后instanceof将返回您的对象是否确实是该类型的实例

'use strict';

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

var err = new InvalidCredentialsError("Hello, world!");

console.log(err instanceof InvalidCredentialsError); // true

注意 const errClass = InvalidCredentialsError;只会为您的类型创建别名,因此您可以执行此操作...

var err = new errClass("Hello, alias");
console.log(err instanceof errClass); // true