【Ts踩坑】关于子类继承Error/Array/Map等造成无法访问子类中声明的方法问题

问题描述

// 举个栗子
class AxiosError extends Error {
    constructor(message: string) {
        super(message)
    }

    getError() {
        return "error: " + this.message
    }
}

上述,我们在ts中使用es6的语法去声明了一个AxiosError类,并且在当中声明了一个方法,但是会遇到以下两个问题:

  • getError这个方法为undefined
  • new AxiosError() instanceof AxiosError 返回了一个false

 

解决办法

class AxiosError extends Error {
    constructor(message: string) {
        super(message)
    
        // Set the prototype explicitly
        Object.setPrototypeOf(this, AxiosError.prototype)
    }

    getError() {
        return "error: " + this.message
    }
}

这样,任何一个AxiosError的子类都会手动的去设置prototype,也正是如此,我们要注意在代码运行时,如果有相关需要,我们不能再去使用Object.setPrototypeOf,而是要使用__proto__去代替相应的功能!

另外:在IE10及以下版本,有兼容性问题,要使用AxiosError.prototype去代替this,但也存在的问题是prototype chain不能正确解决!

posted @ 2019-08-23 19:32  林璡  阅读(890)  评论(0编辑  收藏  举报