当我试图向某人展示 js 对象中的公共(public)属性和私有(private)属性时,我突然感到非常困惑。
让我们采用以下对象:
function person() {
var name = 'joe';
var age = '32';
this.setName = function (name) {
this.name = name;
}
this.setAge = function (age) {
this.age = age;
}
this.getName = function () {
return this.name;
}
this.getAge = function () {
return this.age;
}
}
var newBuddy = new person();
我预计 newBuddy.name 和 newBuddy.age 在此阶段未定义。他们是。到目前为止一切顺利!
但是,请看以下内容:
newBuddy.setName('matt'); //I use my setName() method to change the name.
newBuddy.name; // returns "matt" -> that' what I cannot understand.
// I was expecting not to be able to access this property. Ever. See below.
我的思考过程是: 如果我声明了 this.name = 'joe' 而不是 var name = 'joe',我会理解 newBuddy.name 首先返回 'joe',然后返回 'matt'。公共(public)属性(property)将是可以访问的。
但是因为我用“var name”声明了我的属性,所以我不应该无法访问这个属性吗?
我的理解是,获取名称的唯一方法是使用 newBuddy.getName() 调用我的 this.getName() 方法;
对我来说,在该对象中,newBuddy.name 应该始终返回未定义。
在那一刻之前我对使用对象充满信心,但我真的不知道我错过了什么。
我使用 Firefox 31.0 在我的 firebug 2.0.2 控制台中运行了该代码,我怀疑它有什么区别。
最佳答案
您不应该使用this
,您已经为name
和age
声明了本地(私有(private))变量:
function Person() {
var _name = 'Joe';
var _age = 32;
this.setName = function (name) {
_name = name;
}
this.setAge = function (age) {
_age = age;
}
this.getName = function () {
return _name;
}
this.getAge = function () {
return _age;
}
}
关于javascript 对象私有(private)属性的行为就像公共(public)属性一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25296593/