Reputation: 98
I would like to increment property SCountDown
of an object pomodoro
with
method customization
, which has an argument chooseSession
and this method
is called within sessionPlus
method passing SCountDown
as an argument.
when i call sessionPlus
method , SCountDown
property increments for
once and when it is called for second time and so on , It doesn't increment.
Here's my code:
pomodoro = {
SCountDown: 0,
customization: function(chooseSession) {
chooseSession++;
console.log(chooseSession);
},
sessionPlus : function() {
this.customization(this.SCountDown);
}
}
pomodoro.sessionPlus(); // it returns 1 , this is what i needed but
pomodoro.sessionPlus(); // it also returns 1, but what i need is 2.
Upvotes: 3
Views: 549
Reputation: 776
pomodoro = {
SCountDown: 0,
customization: function() {
console.log(this.SCountDown);
},
sessionPlus : function() {
this.SCountDown=this.SCountDown+1;
this.customization();
}
}
pomodoro.sessionPlus(); // it returns 1 , this is what i needed but
pomodoro.sessionPlus(); // it also returns 1, but what i need is 2.
Upvotes: 1
Reputation: 1156
JavaScript uses pass by sharing and since SCountDown is a primitive value (integer) it cannot be referenced in the way you are attempting to. It's always going to log as 1 because you will always be passing in the primitive value 0 and then incrementing that. You need to reference this.SCountDown
directly instead of chooseSession
.
var pomodoro = {
SCountDown: 0,
customization: function(chooseSession) {
console.log(chooseSession);
},
sessionPlus: function() {
this.SCountDown++;
this.customization(this.SCountDown);
}
}
pomodoro.sessionPlus();
pomodoro.sessionPlus();
Upvotes: 2
Reputation: 34234
When you pass this.SCountDown
to customization
, you pass its value (which is zero). Then, this value is incremented by 1 and it is outputed. The actual value of this.SCountDown
never changes.
JavaScript passes primitives by value.
It means that there is no way to modify the primitive by passing it to a function.
function modify(a)
{
a = a * 2;
}
var x = 2;
modify(x);
console.log(x); // 2
However, you can modify the inner properties of passed objects since JS uses call-by-sharing strategy.
Therefore, you can do the following:
function modify(o)
{
o.val = o.val * 2;
}
var x = { val: 2 };
modify(x);
console.log(x.val); // 4
Upvotes: 1
Reputation: 825
Try this code. You need increment this.SCountDown not chooseSession
pomodoro = {
SCountDown: 0,
customization: function(chooseSession) {
console.log(chooseSession);
},
sessionPlus: function() {
this.SCountDown++;
this.customization(this.SCountDown);
}
}
pomodoro.sessionPlus();
pomodoro.sessionPlus();
Hope this will help you.
Upvotes: 1