ES6类实现索引器像数组 [英] ES6 Classes implement indexer like arrays

查看:198
本文介绍了ES6类实现索引器像数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现索引器从数据属性获取索引为js数组的元素。我听说过es6代理,但我无法将其实现到我的课堂。是否可能现在或应该等待更多来与es7 ...

I want to implement indexer to get elements from data property with index as js arrays. I heard about es6 proxies but i couldn't implement it to my class. Is it possible now or should i wait more to come with es7...

class Polygon {
constructor() {
    this.data = new Set(arguments)
}

[Symbol.iterator](){
    return this.data[Symbol.iterator]()
}

add(vertex){
    this.data.add(vertex)
}

remove(vertex){
    this.data.delete(vertex)
}

get perimeter(){

}

get area(){

}
}


let poly = new Polygon()
let first_vertex = poly[0]


推荐答案

AFAIK没有像索引到任意对象的建议,所以是你必须去代理。

AFAIK there is no proposal for something like "indexing" into arbitrary objects, so yes, you would have to go with proxies.

我无法真正测试,因为没有环境似乎支持类和代理,但在理论上, / del>你必须从构造函数返回新的代理对象。测试在Chrome v52。

I couldn't really test this since no environment seems to support both classes and proxies, but in theory, you'd have to return the new proxied object from the constructor. Tested in Chrome v52.

示例:

class Test {
  constructor(data) {
    let self = this;
    this.data = data;
    this.foo = 'bar';

    return new Proxy(this, {
      get(target, prop) {
        if (Number(prop) == prop && !(prop in target)) {
          return self.data[prop];
        }
        return target[prop];
      }
    });
  }
}

var test = new Test([1,2,3]);
console.log(test[0]); // should log 1
console.log(test.foo); // should log 'bar'

这篇关于ES6类实现索引器像数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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