Reputation: 2149
I am basically from java background so I wrote a JavaScript code in which a variable act as private variable , Here is my code
var myObject = function(){
var teamScore = 0;
return {
playSix: function() {
teamScore += 6
},
playFour: function() {
teamScore = teamScore +4
},
getScore: function(){
return teamScore;
},
getMScore : teamScore
}
}();
myObject.playSix();
alert ("What is the team score :" + myObject.getScore())
alert ("What is the M-score :" + myObject.getMScore)
Desired output is
What is the team score : 6 ; What is the M-score : 6
But the actual output is
What is the team score : 6 ; What is the M-score : 0
Why M-score is 0 ?
Upvotes: 0
Views: 58
Reputation: 4778
When you define the object, you are setting teamScore = 0
and then getMScore : teamScore
. In other words, the value of teamScore
will be used to initialise getMScore
.
Note that "value" is the key word here - this code is not assigning a reference to the teamScore
variable, it's literally just copying the current value from one to the other. getMScore
will not change if teamScore
does, because the two values are independent.
Upvotes: 1
Reputation: 1310
If you look closely, getScore is a function which when called return the current value of teamScore. So, when you called myObject.playSix(); teamScore would become 6. Now calling getScore would return current value of teamScore = 6
On the other hand, getMScore gets assigned to initial value of teamScore (which is 0) and remains the same. Hope it makes sense.
Upvotes: 2
Reputation: 733
This happens because getScore
is a function, and it will get actual result of teamScore
all the time you call it. But getMScore
is just simple static value which you have set before returning. Pay attention that getMScore
is not some kind of "shortcut" or "pointer" to teamScore
, it's just simple value.
To fix this you should write getMScore as function, for example:
getMScore : function() { return teamScore; }
and call it like this:
alert ("What is the M-score :" + myObject.getMScore())
Upvotes: 3
Reputation: 36703
getMScore
is initialized with 0
Because when you defining the object
the teamScore
is equal to 0
and getMScore : teamScore
will also get a 0
doesnt matter you change it afterwards.
Upvotes: 2
Reputation: 700172
That's because the getMScore
is initialised to zero, and never changes.
The property getMScore
is not a reference to the teamScore
variable, it's only initialised with the value of the teamScore
variable at the time that the object is created. When the teamScore
variable is changed, the getMScore
property is unaffected.
Upvotes: 4
Reputation: 15715
The getMScore, your are referring to, in myObject
, is already assigned to 0, when teamscore initially was 0,
So even if you change value for teamscore, it will still return the value which was returned prior to changing the value of teamscore
Upvotes: 2