Extend native JavaScript array

后端 未结 10 867
情书的邮戳
情书的邮戳 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:54

    With purpose to overcome the problem of extension of the native Array class, I took advantage of a decorator.

    function extendArray(constructor: Function) {
        Object.getOwnPropertyNames(constructor.prototype)
            .filter(name => name !== 'constructor')
    .forEach(name => {
        const attributes = Object.getOwnPropertyDescriptor(constructor.prototype, name);
        Object.defineProperty(Array.prototype, name, attributes);
      });
    }
    
    @extendArray
    export class Collection extends Array {
      constructor(...args: T[]) {
        super(...args);
      }
      // my appended methods
    }

    BTW This decorator can be made more generic (for other native classes) if to use a decorator factory.

提交回复
热议问题