美文网首页
TypeError: t.printEleis not a fu

TypeError: t.printEleis not a fu

作者: 前端老邹_伯通 | 来源:发表于2020-01-20 18:34 被阅读0次
  • 在 TS 中 继承 Array ,并添加自定义方法:
class MyArray extends Array {
    constructor() {
        super();
    }

    public printEle(): void {
        for (let i = 0; i < this.length; i++) {
            console.log(this[i]);
        }
    }
}

let t = new MyArray();
t.push(1, 2, 3);
t.printEle();
  • 运行时 会报错
TypeError: t.printEleis not a function
  • 解决方案:在 TS 中 继承 Array 或 Error,需要在【构造函数】中 修改 注册 【当前类的 原型】
class MyArray extends Array {
    constructor() {
        super();
        // 注册 MyArray类的原型
        Object.setPrototypeOf(this, MyArray.prototype)
    }

    public printEle(): void {
        for (let i = 0; i < this.length; i++) {
            console.log(this[i]);
        }
    }
}

let t = new MyArray();
t.push(1, 2, 3);
t.printEle();

参考:https://blog.simontest.net/extend-array-with-typescript-965cc1134b3

相关文章

网友评论

      本文标题:TypeError: t.printEleis not a fu

      本文链接:https://www.haomeiwen.com/subject/qizjzctx.html