Reputation: 451
In the following JavaScript code, I use a closure to build an object. When I call personA.addFriend()
a few times, call personA.ListOfFriends()
, and then print the value of personA.numOfFriends
, it still gives me 0 instead of 2.
Why does it not get the value 2?
function person(name) {
var name = name;
var friends = [];
var numOfFriends = 0;
return {
sayMyName: function() {
return name;
},
sayHello: function() {
return "hello" + " " + name;
},
addFriend:function(obj){
numOfFriends += 1;
friends.push(obj)
return "you just became friend with " + obj.sayMyName();
},
listFriends: function(){
return name + "! you have " + numOfFriends + " friends";
},
name: name,
friends: friends,
numOfFriends: numOfFriends
}
}
var personA = person("Ali")
var personB = person("Huda")
var personC = person("Mona")
personA.addFriend(personB);
personA.addFriend(personC);
personA.listFriends();
console.log(personA.numOfFriends);
Upvotes: 1
Views: 67
Reputation: 350290
When you assign numOfFriends
to the property with the same name, you will have two separate values, both living their own lives. When later the numOfFriends
variable is incremented, the property will not change.
To fix this, you should not reference the variable in the methods, but the property. So do this:
this.numOfFriends+=1;
^^^^
And:
return name+"! you have "+this.numOfFriends+" friends";
^^^^
Do the same with the other variable name
that could suffer from the same problem (if you would have a method to change it).
Upvotes: 2