Javascript builder pattern using private variables

China☆狼群 提交于 2019-12-10 18:19:59

问题


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

回答1:


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

var Person = function () {
    var _firstName, _lastName

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

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

    return _self;
}

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

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

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



来源:https://stackoverflow.com/questions/33963800/javascript-builder-pattern-using-private-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!