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. This question and answer suggests that I can use Object.defineProperty inside the person constructor in order to access private variables, but it doesn't work - instance.fullName is always undefined.
How can I get this working so that the builder pattern variables remain private, but the public accessor has access to them throughout the build chain?
var Person = function () {
var _firstName, _lastName
Object.defineProperty(this, "fullName", {
get: function () {
return _firstName + ' ' + _lastName;
}
});
return {
firstName: function (n) {
_firstName = n
return this
},
lastName: function (n) {
_lastName = n
return this
}
}
}
var x = new Person().firstName('bob').lastName('dole');
console.log(x.fullName); // always undefined
Personis different from thethison whichObject.defineProperty()is called.Object.defineProperty()doesn't really feel like the right way to go about this anyway.this._firstNameetc. doesn't work with this design.