Search code examples
javascriptscopeiife

Make an IIFE return variables for only some other IIFES


I was wondering if we can declare a variable in one IIFE and the return it but make it available for another specific IIFE? Here is an example!

So I have

const iife1 = (()=>{
const x = 10;
return x
})()

const iife2 = (()=>{/* MAKE X AVAILABLE ONLY IN THIS FUNCTION */})()
const iife3 = (()=>{/* HERE X CANNOT BE CALLED */})()

Maybe you would say just not to pass the variable x in the iif3 as an argument, but I was wondering if there is a conditional way we can achieve it when returning the variable from iif1, so the iif1 will know for which functions it returns its properties or methods before actually has returned!

My goal is to create an IIFE which in it I will declare all the variables that I am going to use in my project. Then for each variable, I want to have a proper condition so that when the IIFE with the variables returns the function has already decided in which scope will sent the variables for use! I don't know if this approach makes sense but as is always being said I am trying not to populate the global scope.

Codepen


Solution

  • One of the (probaby dozen) ways to achieve that is by using a Proxy. First IIFE would create a proxy object through which you'd access its properties. After calling the revoke(), you will no longer be able to access any of the proxy's props.

    As people have stated in their comments, there are probably much easier ways for you to achieve the wanted result, but you haven't presented the actual problem clearly.

    const { proxy, revoke } = (() => {
        const x = { test: 'test' };
        const revocable = Proxy.revocable(x, {
            get: (target, name) => name
        });
    
        return revocable;
    })();
    
    const test1 = (proxy => {
        console.log('TEST 1', proxy.test);
    })(proxy);
    
    revoke();
    
    const test2 = (proxy => {
        console.log('TEST 2', proxy.test); // can't access
    })(proxy);
    

    Fiddle: https://jsfiddle.net/ay92L1r6/6/