JavaScript中的自定义阵列式getter [英] Custom Array-like getter in JavaScript

查看:151
本文介绍了JavaScript中的自定义阵列式getter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的ES6类,如下所示:

I have a simple ES6 class, like so:

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

我想让它成为Ring的索引(1,2,3)[3] 返回1,新环(1,2,3)[ - 1] 返回3,依此类推。这是否可能在ES6?如果是这样,我该如何实现?

I want to make it so that the indexing for Ring objects wraps, so that new Ring(1, 2, 3)[3] returns 1, new Ring(1, 2, 3)[-1] returns 3, and so on. Is this possible in ES6? If so, how would I implement it?

我已经阅读了有关代理,这允许一个完全定制的getter,但是我无法弄清楚如何应用代理上课我没有管理这个:

I've read about proxies, which allow a completely customized getter, but I can't figure out how to apply a proxy to a class. I did manage this:

var myRing = new Proxy (Ring.prototype, {
    get: function (target, name) {
        var len = target.length;
        if (/^-?\d+$/.test(name))
            return target[(name % len + len) % len];
        return target[name];
    }
});

myRing 现在是支持的Ring对象包装指数。问题是我每次都要定义这样的Ring对象。有没有办法将此代理应用到类中,以便调用新的Ring()返回它?

myRing is now a Ring object that supports wrapping indices. The problem is that I'd have to define Ring objects like that every time. Is there a way to apply this proxy to the class such that calling new Ring() returns it?

推荐答案

基本上是

class ProxyRing extends Array {
  constructor(...args) {
    super(...args)

    return new Proxy(this, {
      get: function (target, name) {
          var len = target.length;
          if (typeof name === 'string' && /^-?\d+$/.test(name))
              return target[(name % len + len) % len];
          return target[name];
      }
    });
  }

  insert (item, index) {
      this.splice(index, 0, item);
      return this;
  }
}

这篇关于JavaScript中的自定义阵列式getter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆