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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top