[Ts] on the stepped pit subclass inherits Error / Array / Map and other causes can not access a subclass method declared in question

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!

Also: In IE10 and below, there are compatibility issues, you want to use AxiosError.prototype to replace this, but the problem is not resolved properly prototype chain!

Guess you like

Origin www.cnblogs.com/fe-linjin/p/11402182.html