Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to an IIFE

Tags:

javascript

What's the correct syntax for passing arguments to an IIFE stored in a variable?

Example below tells me that foo is not defined, regardless on if I call the function or not:

var bar = (function(foo){

    return { 
        getFoo: function(){
            return foo;
        } 
    }

})(foo);

console.log(bar.getFoo(1));

http://jsfiddle.net/eSTkL/

like image 271
Johan Avatar asked Aug 31 '13 20:08

Johan


People also ask

How do you pass arguments in IIFE?

The foo that you're passing to the IIFE isn't defined. You should define foo in the outer variable environment first. var foo = "foobar"; var bar = (function(foo){ return { getFoo: function(){ return foo; } } })(foo); Or just define it directly in the argument position.

Can IIFE have arguments?

Not only IIFEs can return values, but IIFEs can also take arguments while they are invoked. Let's see a quick example.

When would you use an IIFE?

An IIFE is a good way to secure the scope. You can use IIFEs to prevent global variables' definition issues, alias variables, protect private data, and avoid conflicts of using many libraries that export the same object name.

Are IIFE still used?

Most uses for IIFE's have disappeared because block scoped variables solve the most common thing that IIFE's are used for. That said, there are still some less common reasons to occasionally use one (though I haven't encountered one of those in my code yet).


1 Answers

The IIFE is immediately invoked. You are passing foo to it at the moment of invocation, and I suppose it's undefined.

What gets stored in bar is not the IIFE, but the object returned by the IIFE, that doesn't have anything to do with foo (beside having access to it via closure). If you want foo to be 1, don't pass that value to getFoo, but to the IIFE itself:

var bar = (function(foo){

    return { 
        getFoo: function(){
            return foo;
        } 
    }

})(1);

console.log(bar.getFoo()); // 1

If you want a getter and a setter (actually, getter/setter-like functions), use this:

var bar = (function(foo){

    return { 
        getFoo: function(){
            return foo;
        },
        setFoo: function(val) {
            foo = val;
        }
    }

})(1);

console.log(bar.getFoo()); // 1
bar.setFoo(2);
console.log(bar.getFoo()); // 2
like image 125
bfavaretto Avatar answered Oct 07 '22 01:10

bfavaretto