Skip to content Skip to sidebar Skip to footer

Javascript Builder Pattern Using Private Variables

I'm trying to create a builder pattern in Javascript that uses private variables, while providing one public accessor (fullName) that returns a mashup of all the other properties.

Solution 1:

As per my comment, change the object passed to defineProperty():

varPerson = function () {
    var _firstName, _lastName

    var _self = {
        firstName: function (n) {
            _firstName = n
            returnthis
        },
        lastName: function (n) {
            _lastName = n
            returnthis
        }
    }

    Object.defineProperty(_self, "fullName", {
        get: function () {
            return _firstName + ' ' + _lastName;
        }
    });

    return _self;
}

var x = newPerson().firstName('bob').lastName('dole');

console.log(x.fullName); // bob dole

http://jsfiddle.net/mattball/peztf9qs/

Post a Comment for "Javascript Builder Pattern Using Private Variables"