【发布时间】:2017-05-11 05:59:33
【问题描述】:
我想创建一个Class,它也是常规Array 的包装器,但是我希望在通过索引引用类实例上的项目时发生一些自定义行为。
演示我想要实现的目标:
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?
现在,我不完全确定这是可能的。我确实设法通过extending Array 提出了我自己的不太好的解决方案。 Proxy 也出现在我的脑海中,但无法找到可行的解决方案。
有没有可能,如果有,最好的方法是什么?
【问题讨论】:
-
您似乎将数组周围的包装器与元素周围的包装器混合在一起。是
c.method()还是c[1].method()?他们绝对应该有不同的类。 -
如果您阅读了我的代码演示的
[Magic.here]位中的推荐,您会意识到我确实想从getter 调用构造函数,如下所示:c[0]返回一个@987654331 @ 基本上,然后可以单独调用method。 -
是的,但是从构造函数的参数名称和使用数组的示例调用中,我意识到
Custom是数组包装器的构造函数,而不是要从 getter 调用的元素的构造函数.
标签: javascript arrays class constructor ecmascript-6