2017-01-17 2 views
3
export class InvalidCredentialsError extends Error { 
    constructor(msg) { 
    super(msg); 
    this.message = msg; 
    this.name = 'InvalidCredentialsError'; 
    } 
} 

위에서 볼 수 있듯이 InvalidCredentialsError을 두 번 쓰고 있습니다. 어떻게 든 생성자 메서드에서 이미 클래스 이름을 가져 와서 설정하는 방법이 있습니까? 또는 객체를 인스턴스화해야합니까?생성자에서 클래스 이름 가져 오기

+1

당신이 찾고 계십니까 [this.co nstructor.name] (http://stackoverflow.com/questions/10314338/get-name-of-object-or-class-in-javascript)? – CodingIntrigue

+0

@CodingIntrigue'this.constructor.name'은 "Error"를 반환합니다. –

+0

이상한. 그것은 현재 클래스 이름을 반환하지 않는 이유를 알 수 없기 때문에'Error'를 서브 클래스화할 때 문제가 될 수 있습니다. – CodingIntrigue

답변

3

네이티브 ES6 클래스를 지원하는 브라우저에서 this.constructor.nameInvalidCredentialsError을 표시합니다. Babel 코드를 번역하면 오류이 표시됩니다.

없이 (클래스 지원하는 크롬이나 다른 브라우저에서 사용) 바벨 : 바벨로

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

관련 문제