Custom Array-like getter in JavaScript

后端 未结 3 1011
无人及你
无人及你 2021-02-14 05:28

I have a simple ES6 class, like so:

class Ring extends Array {
    insert (item, index) {
        this.splice(index, 0, item);
        return this;
    }
}
         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-14 06:21

    You basically have two choices:

    • Wrap a Proxy around each instance

      const handler = {
          get(target, name) {
              var len = target.length;
              if (typeof name === 'string' && /^-?\d+$/.test(name))
                  return target[(name % len + len) % len];
              return target[name];
          }
      };
      class Ring extends Array {
          constructor() {
              super()
              return new Proxy(this, handler);
          }
          …
      }
      
    • wrap a Proxy around the prototype of your class

      class Ring extends Array {
          constructor() {
              super()
          }
          …
      }
      Ring.prototype = new Proxy(Ring.prototype, {
          get(target, name, receiver) {
              var len = target.length;
              if (typeof name === 'string' && /^-?\d+$/.test(name)) {
                  if (+name < 0)
                      return receiver[(name % len) + len];
                  if (+name > len-1)
                      return receiver[name % len];
              }
              return target[name];
          }
      });
      

提交回复
热议问题