0

This might be a stupid question but I have looked everywhere and coming to SO as the last resort. My doubt is an IIFE function usually looks like this

var me = (function() { /*code*/} )();
me();                       

I have not seen any code that has variables passed down into it so far. Is it possible to pass down values to an IIFE function? I have already tried using

var Person = (function(name,age){
    this.name = name;
    this.age = age;
     }());
  Person("Bob Smith", 30); 

which gives me an undefined error.

So is there a way to pass down these values into an IIFE or should it be avoided?

Bazinga777
  • 5,140
  • 13
  • 53
  • 92
  • 1
    Why are you using an IFEE to define a constructor? At least you should return a function! In your case Person returns undefined, you cannot use it as a constructor – Niccolò Campolungo Sep 04 '13 at 19:13
  • Thanks, I'm still quite confused on when to use IIFEs. – Bazinga777 Sep 04 '13 at 19:19
  • 1
    IIFE is a function which is instantly invoked. You can set your params in the IIFE itself: `(function(x) {console.log(x);})(123)` will log 123, but doing `var f = function(x) {console.log(x);}; f(123)` produces **exactly the same** result – Niccolò Campolungo Sep 04 '13 at 19:32
  • Thanks, it's starting to make sense but is it possible to pass down values to an IIFE ? lets say I want to add two numbers by passing down the values a and b. Sorry, if it sounds very stupid. – Bazinga777 Sep 04 '13 at 19:39
  • I think you are a bit confused about functions in JS, I recommend you these readings: http://benalman.com/news/2010/11/immediately-invoked-function-expression/ http://stackoverflow.com/questions/8228281/what-is-this-construct-in-javascript – Niccolò Campolungo Sep 04 '13 at 19:44
  • Thanks, I will. Thank you for your patience. – Bazinga777 Sep 04 '13 at 19:48

1 Answers1

1

This would be an IIFE with parameters:

(function (a, b) {
    alert(a + b);
}('hello', ' world'));


What you seem to be doing, as others said, is a constructor, so there's no need for them there.

You could do a constructor this way if you wanted:

function Person(name, age) {
    this.name = name;
    this.age = age;
}

var bob = new Person('Bob Smith', 30);

You could do an anonymously invoked constructor, but that's pointless since it's a one-use type of deal, and you wouldn't need a constructor for that.

Joe Simmons
  • 1,828
  • 2
  • 12
  • 9