user2294256
user2294256

Reputation: 1049

issue with self-invoking function in js

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

Answers (3)

MACMAN
MACMAN

Reputation: 1971

You have to assign name like this

person.name="abc";

Now try it it will output abc.

Upvotes: 0

Arun P Johny
Arun P Johny

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

HMR
HMR

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

Related Questions