14

I want to implement indexer to get elements from data property with index as JavaScript 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]
Mikael Dúi Bolinder
  • 2,080
  • 2
  • 19
  • 44
moleschott
  • 161
  • 1
  • 4

1 Answers1

20

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

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.

Example:

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'
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Yes. this is the behaviour that i want. Do you know any platform that supports es6 proxies? – moleschott Sep 17 '15 at 06:08
  • Firefox seems to support Proxies but not `class` syntax. You can try it with normal constructor functions though. – Felix Kling Sep 17 '15 at 06:25
  • 2
    I tested your example code with firefox nightly and it works as expected. Now wish to see this support in node.js as soon as possible. Thanks @FelixKling – moleschott Sep 17 '15 at 06:38
  • target could be used in place of self I think, they show strict equality target === self – Valen Jul 20 '21 at 13:36