Search code examples
javascriptoopencapsulation

Why is the private variable assigned twice in this example of encapsulation?


In this example of encapsulation, why is name assigned to the private variable _name on line 9? It seems redundant to me, since in line 2, name was already assigned to _name and there haven't been any changes to _name or name..

Or am I reading this wrong and is name the private variable?

function Person(name) {
    var _name = name;
    return {
        name: function (name) {
            if(!name) {
                return _name;
            }

            _name = name;
        }
    };
}

Solution

  • There are two names. One is a parameter to function Person, and denotes the value _name is created and initialized with. The second is a parameter to the anonymous function stored as name member of the object, and it's the parameter passed to the getter/setter to update the value of the private variable (or get the current value if not supplied). Consider:

    var someone = new Person("alice");
    someone.name("bob");
    console.log(someone.name()); // output: bob