I come to learn JavaScript from the Ruby background, so I had trouble understanding (and putting this in words) why my code does not produce the results that I need. I ran this on pythontutor.com to see a step-by-step description of what is happening, and this confirms my suspicions. However, I do not know exactly why this is so.
I am creating a thermostat and it should return βgreenβ when the temperature is below 18dC. In my penultimate line, console.log has a value of 17, which is correct, however, when I call thermostat.displayColor on the last line, it still says yellow. The code exits there and does not return via this.displayColor = this.currentColor() , which I expect from it (since it did this on first run to determine the initial color as "yellow".
The code works correctly and returns "green" if I modify the code to directly call the prototype method this.currentColor() , however I just want to know why it does not allow me to do it the way I wrote below.
I am not sure of the terminology to describe this problem, so I apologize in advance for the fact that my title was not accurate.
var DEFAULT_TEMP = 20; function Thermostat(){ this.temperature = DEFAULT_TEMP; this.maxTemp = 25; this.powerMode = 'on'; this.displayColor = this.currentColor() }; Thermostat.prototype.downButton = function(){ if (this.temperature === 10){ throw new Error('temp cannot be lower than 10dC'); }; this.temperature --; }; Thermostat.prototype.currentColor = function() { if ((this.temperature >= 18) && (this.temperature < 25)) { return 'yellow' } else if (this.temperature < 18) { return 'green' } else { return 'red' } }; var thermostat = new Thermostat(); for (var i = 1; i <= 3; i++) { thermostat.downButton(); }; console.log("spec file test green, temp should be 17 and is:" + thermostat.temperature) console.log(thermostat.displayColor);
source share