Reputation: 1049
var person = function () {
// Private
var name = "David";
return {
getName : function () {
return name;
},
setName : function (newName) {
name = newName;
}
};
}();
console.log(person.name);
Question:
why it shows: Undefined in console?
Upvotes: -1
Views: 82
Reputation: 1971
You have to assign name like this
person.name="abc";
Now try it it will output abc.
Upvotes: 0
Reputation: 388436
You need to use
console.log(person.getName());
because name
is a closure variable which cannot be accessed outside the scope of the anonymous function.
The variable person
holds the value returned from the iife which is an object with properties getName
and setName
, so those are the only properties you can access from person
reference.
Demo: Fiddle
Upvotes: 5
Reputation: 39320
You're using a pattern to simulate privates, the title of your object person
suggest multiple instances so I would advice against using this pattern as it breaks JavaScript's infrastructure to create OOP code (prototype) completely.
You could use the constructor function instead and mark privates with an underscore like _myvar
Here is some code that you can play with to understand prototyping in JS
Prototypical inheritance - writing up
Upvotes: -1