Search code examples
javascriptarraysscopeglobal-variables

How to variable shadow Javascript Array?


I am running a self invoked function, and I would like to change the Array object in it, and only in its scope.

        var foo = "Foo Outer";
        (function(){
            var foo = 'Foo Inner !';
            console.log('INNER>',foo);
            // prints INNER> Foo Inner !
            var Array = {};
            var Array = Object.getPrototypeOf([]).constructor;
            Array.prototype.filter = ()=>{return "Array filter inner"}        
            console.log('INNER> array filter literal:', [1,2,3].filter(x=>x));
            // prints INNER> array filter literal:Array filter inner 
        })()
        console.log('OUTER> foo ', foo);
        // prints OUTER> foo Foo outer
        console.log('OUTER> Array filter', [1,2,3].filter(x=>x));
        // prints OUTER> Array filter Array filter inner
        // I want -> 
        // OUTER> Array Filter [1,2,3]

How can I variable shadow Array and its methods only inside the scope of the self invoked function, while keeping it the same for the rest of the script ?


Solution

  • Apparently the answer (as was written in the comment by @Bergi) is that it isn't possible to variable shadow Array)