我想创建一个Class
,它也是一个常规Array
的包装,但是我希望在通过索引引用类实例上的项目时发生一些自定义行为。自定义类似于ES6类的阵列的吸气器
演示我想达到的目标:
class Custom {
constructor (arr) {
this.arr = arr;
}
method (str) {
this.arr.forEach(item => {
console.log(`${item} ${str}`);
})
}
[Magic.here]() {
// this part should invoke the constructor of this class with a single item of the array passed into it as an array of one as argument.
}
}
let c = new Custom(['something', 'other thing', 'hello?']);
c[1].method('exists?') // -> other thing exists?
现在,我不能完全肯定这是可能的。我设法想出了我自己的不太好的解决方案,通过extend
ing Array
。 Proxy
也进入了我的想法,但不能得到一个工作解决方案。
这是可能的,如果是这样,最好的方法是什么?
你似乎正在围绕着元素周围的包装混合包装。它会是'c.method()'或'c [1] .method()'?他们绝对应该有不同的阶级。 – Bergi
如果你阅读了我的代码演示中的[Magic.here]'部分的推荐内容,你会意识到我确实想从getter调用构造函数,就像这样:'c [0]''returns a'new自定义(this.arr [0])'基本上,然后可以单独调用'method'。 –
是的,但从构造函数的参数名称和数组的示例调用我意识到'Custom'是数组包装器的构造函数,而不是从getter调用的元素的构造函数。 – Bergi