How can I extend the Array class and keep its implementations

前端 未结 2 1787
故里飘歌
故里飘歌 2021-01-14 07:10

I\'d like to add some functions to the Array class (I\'d rather not have them as functions external to the class since it would ideally be discoverable when typing .

2条回答
  •  深忆病人
    2021-01-14 07:33

    There is no need to set the prototype. The error occurs because the constructor runs a second time when the map is called and the length of the array is passed as an argument, so when you try to spread the argument on the super call, it throws an error because a number is not iterable.

     constructor(items?: Array) {
    
        console.log(`I've received `, items);
        items = items || [];
        super(...items);
        console.log(`Now i'm this`, this); //
        // Object.setPrototypeOf(this, List.prototype);
    
     }
    

    Why does it happen? No idea! I do not have enough points yet, otherwise I'd put this as a comment! :-)

    If you change the constructor to use ... to gather the arguments nothing will blow up:

     constructor(...items: Array) { //...
    

提交回复
热议问题