Reputation: 35194
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));
Upvotes: 24
Views: 24159
Reputation: 21
const bar = (foo => ({ getFoo: _ => foo }))("foobar");
console.log(bar.getFoo())
Upvotes: 1
Reputation: 124
Why not simply:
var bar = (function(){
return {
getFoo: function(foo){
return foo;
}
}
})();
console.log(bar.getFoo(1));
Works for me.
Upvotes: 5
Reputation: 71918
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
Upvotes: 50
Reputation: 3543
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.
var bar = (function(foo){
return {
getFoo: function(){
return foo;
}
}
})("foobar");
Also note that you're passing a value to getFoo()
, but you're not actually using it in the method.
// v----never gets used
bar.getFoo(1)
Upvotes: 5