this is one of my first questions to ask on this website so please do tell me if I am approaching this the wrong way.
Anyways, in my obj i've created (dog), I have a "live" function that counts the age of my dog starting from age (5) by using the setInterval feature of javascript. So calling the the function by typing "dog.live()" will proceed to perform the "if" side of the function until the dog's age gets to 15, then it will proceed to perform the "else" part of the function by telling you how long the dog has been dead for.
var dog = {
age : 5,
live : function() {
setInterval(function() {
var timer = this.age += 1;
if (this.age < 15) {
console.log("Dog lives another day at age " + this.age);
} else {
console.log("Dog has been dead for " + (timer - 15) + " years");
}
}.bind(dog), 1000);
}
}
dog.live();
"Dog lives another day at age 6"
"Dog lives another day at age 7"
...
"Dog has been dead for 0 years"
"Dog has been dead for 1 years"
Now, I understand how, at the "else" part of the function inside the setInterval, it increments the age by using the "timer" variable. However, I am stumped at how the "if" part of the function which tells how old the dog is, increments itself? As far as I can tell, it would not increment by itself because "var timer = this.age += 1;" is just declaring a variable and it's not performing anything itself. I would like to know how the dog's age get incremented while it is performing the "if" side of the function.
Again, if i'm asking this question the wrong way or if a question like this isn't permitted, please feel free to let me know and i'll further try and improve my future questions, thank you!