Javascript函数和原型 - 通过调用方法的基本路由问题

ugo*_*chi 5 javascript prototype function

我正在接近从Ruby背景学习JavaScript,所以我在理解(并将其置于文字中)时遇到了一些麻烦,为什么我的代码无法产生我需要的结果.我在pythontutor.com上运行了这个,看看发生了什么的逐步演练,这证实了我的怀疑.但是,我不确定为什么会这样.

我正在建造一个恒温器,一旦温度低于18℃,它应该返回"绿色".在我的倒数第二行,console.log是17这是正确的,但是当我thermostat.displayColor在最后一行调用它仍然说黄色.代码在那里终止,并且不会返回this.displayColor = this.currentColor()我期望它(因为它在第一次运行时执行此操作以将起始颜色定义为"黄色".

代码正常工作并返回'绿色'如果我改变代码直接调用原型方法this.currentColor(),但我只是想知道为什么它不让我按照我在下面写的方式来做.

我不确定描述这个问题的术语,所以提前道歉我的标题不准确.

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); //this should be green, but it is yellow!
Run Code Online (Sandbox Code Playgroud)

Rob*_* M. 3

您应该调用该currentColor()方法,displayColor仅在构造函数中设置(此时温度为20)并且在温度变化时不会更新。

将颜色设置添加到downButton方法中可能是有意义的:

Thermostat.prototype.downButton = function(){
  if (this.temperature === 10){
    throw new Error('temp cannot be lower than 10dC');
  };
  this.temperature --;
  this.displayColor = this.currentColor();
};
Run Code Online (Sandbox Code Playgroud)