Reputation: 51
As I was trying to show someone public vs private properties in a js object, I got very confused all of a sudden.
Let's take the following object:
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();
I expect newBuddy.name and newBuddy.age to be undefined at this stage. They are. So far so good!
However, look at the following:
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.
My thought process is: If I had declared this.name = 'joe' instead of var name = 'joe', I would understand that newBuddy.name returns 'joe' first, then 'matt'. The public property would have been accessible.
But because I declared my property with "var name", shouldn't I not be able to access this property?
My understanding was that the only way to get the name would be by calling my this.getName() method with newBuddy.getName();
To me, in that object, newBuddy.name should always return undefined.
I felt confident using objects until that moment, and I really cannot figure out what I am mising.
I ran that code in my firebug 2.0.2 console using Firefox 31.0, I doubt it makes any difference.
Upvotes: 2
Views: 628
Reputation: 21
The problem lies with how you are assigning/accessing the variables within the getter and setter methods.
this.setName = function (name) {
this.name = name;
}
When you set this.name
, you are creating the property on the person
instance. If you wish to set the value of the local variable name
, you simply omit this
.
ex:
this.setName = function (name) {
name = name;
}
This, however, will still not function correctly, as the parameter name
has the same name as the 'private' property, which means the identifier name
will always resolve to the parameter name
instead of the 'private' property. This can be remedied by renaming either the parameter or the private variable. I would simply prefix the private variables with _
:
function person(){
var _name = "Joe";
this.setName = function (name) {
_name = name;
}
this.getName = function () {
return _name;
}
}
Upvotes: 1
Reputation: 94101
You should not use this
, you already declared local (private) variables for name
and age
:
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;
}
}
Upvotes: 1