Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Classes implement indexer like arrays

Tags:

ecmascript-6

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]
like image 607
moleschott Avatar asked Sep 17 '15 05:09

moleschott


1 Answers

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'
like image 170
Felix Kling Avatar answered Jan 01 '23 21:01

Felix Kling