我想实现索引器来从data属性获取元素,索引为JavaScript数组.我听说过ES6代理,但我无法将它实现到我的班级.现在是否可能,或者我应该等待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]
Run Code Online (Sandbox Code Playgroud)
Fel*_*ing 12
AFAIK没有提议将"索引"成任意对象,所以是的,你必须使用代理.
我无法真正测试这个,因为没有环境似乎支持类和代理,但从理论上讲,你必须从构造函数返回新的代理对象.在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'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1564 次 |
| 最近记录: |