我想創建一個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