Custom Array-like getter in JavaScript

后端 未结 3 1010
无人及你
无人及你 2021-02-14 05:28

I have a simple ES6 class, like so:

class Ring extends Array {
    insert (item, index) {
        this.splice(index, 0, item);
        return this;
    }
}
         


        
3条回答
  •  走了就别回头了
    2021-02-14 05:59

    Warning: This is an ugly hack

    This is a rather simple approach when you think about it.

    function ClassToProxy(_class, handler) {
        return (...args) => new Proxy(new _class(...args), handler);
    }
    

    This defined a function ClassToProxy. The first argument is the class you want to add behavior too, and the second is the handler.


    Here's example usage:

    const Ring = ClassToProxy(
    
        // Class
        class Ring {
            constructor(...items) {
                this.items = items;
            }
        },
    
        // Handler
        {
            get: function(target, name) {
                return target.items[name];
            }
        }
    )
    

提交回复
热议问题