musicman Posted April 24, 2016 Share Posted April 24, 2016 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 More sharing options...
Ingolme Posted April 24, 2016 Share Posted April 24, 2016 Variables declared inside a function are only available inside that function. If you try to call addPerson outside the function it won't exist. 1 Link to comment Share on other sites More sharing options...
musicman Posted April 24, 2016 Author Share Posted April 24, 2016 (edited) wow! that simple. thanks Ingolme! Edited April 24, 2016 by musicman Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now