使用私有变量的Javascript构建器模式 [英] Javascript builder pattern using private variables
问题描述
我试图在Javascript中创建一个使用私有变量的构建器模式,同时提供一个公共访问器( fullName
),该访问器返回所有其他属性的混搭。 这个问题和答案表明我可以在人员构造函数中使用 Object.defineProperty
来访问私有变量,但这不起作用- instance.fullName
始终为未定义
。
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
推荐答案
根据我的评论,传递给 defineProperty()
的对象:
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/
这篇关于使用私有变量的Javascript构建器模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!