Typescript 从Array 继承时碰到的问题

class TestArray extends Array<number>
{
    private _values;
    constructor(value) {
        super();
        this._values = value;
       
    }

    TestMethod() {
        alert("hello, world");
    }
}

var testArr = new TestArray([]);
testArr.TestMethod();

上面的代码可以编译通过,运行时提示TestMethod不存在,在构造函数中加上Object["setPrototypeOf"](this, TestArray.prototype); 就好了。

相关的链接

https://github.com/Microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work

 

https://stackoverflow.com/questions/14000645/extend-native-javascript-array

 

标准的Error, Array, Map 都有这个问题。

 

class TestArray extends Array<number>
{
    private _values;
    constructor(value) {
        super();
        this._values = value;
        Object["setPrototypeOf"](this, TestArray.prototype);
    }

    TestMethod() {
        alert("hello, world");
    }
}

var testArr = new TestArray([]);
testArr.TestMethod();

 

posted @ 2019-03-18 10:10  MakeCoder  阅读(656)  评论(0编辑  收藏  举报