ES6 类上的自定义类似数组的 getter

Dán*_*ács 5 javascript arrays constructor class ecmascript-6

我想创建一个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?
Run Code Online (Sandbox Code Playgroud)

现在,我并不完全确定这是可能的。extend我确实通过ing 设法提出了自己不太好的解决方案ArrayProxy我也想到了,但无法找到可行的解决方案。

这是否可能?如果可以,最好的方法是什么?

Ber*_*rgi 1

是的,您正在寻找代理:

const isArrayIndex = str => (str >>> 0) + '' === str && str < 4294967295;
const arrayCustomizer = {
    get(target, property, receiver) {
        var el = Reflect.get(target, property, receiver);
        if (isArrayIndex(property) && el != null)
            el = new Custom(el);
        return el;
    }
}
class Custom {
    constructor(v) {
        this.value = v;
    }
    valueOf() {
        return this.value;
    }
    method(arg) {
        console.log(this.value + " " + arg.replace("?", "!"));
    }
}

let c = new Proxy(['something', 'other thing', 'hello?'], arrayCustomizer);
c[1].method('exists?')
Run Code Online (Sandbox Code Playgroud)