Problem Description
// 举个栗子
class AxiosError extends Error {
constructor(message: string) {
super(message)
}
getError() {
return "error: " + this.message
}
}
Above, we use es6 in ts syntax to declare a AxiosError class, and declares a method in which, but will encounter the following two problems:
- This method is undefined getError
- new AxiosError () instanceof AxiosError returns a false
Solution
class AxiosError extends Error {
constructor(message: string) {
super(message)
// Set the prototype explicitly
Object.setPrototypeOf(this, AxiosError.prototype)
}
getError() {
return "error: " + this.message
}
}
Thus, any manual will AxiosError a subclass to set the prototype, it is the case, we should pay attention to the code runs, if related needs, we can not go use Object.setPrototypeOf, but to use to __proto__ instead of the corresponding function!