javascriptarraysproxy-pattern

How to proxify the instanciation of array with literal notation []


I can detect new instance made via Array() or new Array(). But what about [] ?

const originalArray = Array;
Array = new Proxy(Array,{
    construct(target, args) {
        console.log('new array');
        const newArray = Reflect.construct(originalArray, args);
        return newArray;
    },
    apply(target,thisArg,argArray){
        console.log('apply');
        Reflect.apply(target,thisArg,argArray);
    }
});

var a = [3,2];// no handler
var b = Array(3,2);// apply
var c = new Array(3,2);// new

Solution

  • It is not possible to intercept object creation from literal syntax.

    In fact, this was possible earlier due to a bug, which caused information leaks by making JSON vulnerable to hijacking.