Extend native JavaScript array

后端 未结 10 852
情书的邮戳
情书的邮戳 2020-11-27 22:08

Is there any way to inherit a class from JS native function?

For example, I have a JS function like this:

function Xarray()
{
    Array.apply(this, a         


        
10条回答
  •  清酒与你
    2020-11-27 22:32

    Starting in TypeScript 1.6, you can extend the Array type, see What's new in TypeScript

    Here's an example:

    class MyNewArray extends Array {
        getFirst() {
            return this[0];
        }
    }
    
    var myArray = new MyNewArray();
    myArray.push("First Element");
    console.log(myArray.getFirst()); // "First Element"
    

    If you are emitting to ES5 or below, then use the following code:

    class MyNewArray extends Array {
        constructor(...items: T[]) {
            super(...items);
            Object.setPrototypeOf(this, MyNewArray.prototype);
        }
    
        getFirst() {
            return this[0];
        }
    }
    

    Read more about why this is necessary here.

提交回复
热议问题