0

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 ?

Yaron
  • 1,655
  • 6
  • 20
  • 38
  • 2
    You cannot. `filter` is not a variable that can be shadowed, it's a property of globally shared object. The expression `[1,2,3].filter(x=>x)` never refers to a variable from your scope, it does not use the `Array` variable. (It would if you were to write `new Array(1,2,3).filter(x=>x)`). – Bergi Aug 02 '20 at 18:55

2 Answers2

0

So in javascript, Arrays are passed around by reference. That means that you're always referencing the same "source" thing. If you mutate the array in one place, those changes will be reflected on all the references to that array.

That means that if you want changes to one version of shadow Array to be different than another version, you need to make a copy of it and change that copy.

It also looks like what you're really trying to accomplish here is a local monkey patch of the native array filter method. I believe that the technique you're looking for here is a proxy. Using a proxy, you can intercept the call to the native filter() method and substitute in your own. Proxies were introduced in ECMAScript2015. see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

This previous answer might be most relevant to you Extending Array / Proxy in ES6 correctly?

Brookswift
  • 112
  • 2
0

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

Yaron
  • 1,655
  • 6
  • 20
  • 38