Jump to content

Question on a IIFE style constructor


musicman
 Share

Recommended Posts

Hi,

 

I made a constructor function and wrap it like in IIFE (immediately invoke) style. I create addPerson as a command to call the function. All works fine. But when I use var to create addPerson, it returned undefined. What is the difference between using var and not?

(function (){

            function Person( firstname, age, place ) {
                var elem = this;
                this.firstname = firstname;
                this.age = age;
                this.greeting = { Hello: function(){ console.log( "Hello " + firstname ); }, 
                            YouAre: function(){ console.log( "You are " + age + " years old"); }
                          }
                this.greeting2 = {
                Hello: function(){ console.log( "2. Hello " + elem.firstname ); }, 
                YouAre: function(){ console.log( "You are " + elem.age + " years old" ); }
              }
                
            }

            addPerson = function(firstname, age){ 
                var ab = new Person(firstname, age); 
                return ab;
            };
            
            /*
            
            // If I use "var" to create a new variable,
            // the "addPerson" returned undefined when I call it.
            // Why this happened?
            
            var addPerson = function(firstname, age){ 
                var ab = new Person(firstname, age); 
                return ab;
            }; // Not working!
            
            */
            
        }());

Calling the Person function:

var Clara = addPerson( 'Clara', '20' );
var Jason = addPerson( 'Jason', '24' );

Clara.greeting.Hello();
Jason.greeting.Hello();

Thanks!

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...