javascript - JS 中如何使用变量的困惑

标签 javascript

我是 JS 新手,遇到了 JS 代码,其中实现了 JS 秒表对象的类比。这是代码:

function Stopwatch() { 
  let startTime, endTime, running, duration = 0;

  this.start = function() {
    if (running) 
      throw new Error('Stopwatch has already started.');

    running = true; 

    startTime = new Date();
  };

  this.stop = function() {
    if (!running) 
      throw new Error('Stopwatch is not started.');

    running = false; 

    endTime = new Date();

    const seconds = (endTime.getTime() - startTime.getTime()) / 1000;
    duration += seconds; 
  };

  this.reset = function() { 
    startTime = null;
    endTime = null;
    running = false; 
    duration = 0; 
  };

  Object.defineProperty(this, 'duration', {
    get: function() { return duration; }
  });
}

我想问一些关于上面代码的问题。第一个问题是,当我们在start方法的if语句中使用“running”变量时,“running”的值是否从未定义(默认情况下,因为没有给定值)转换为true?第二个问题,start方法中的if语句之后为什么running被赋值为true。第三个问题,既然start方法中running被赋值为true,那么它的值是否也全局改变了呢?或者全局“running”的值仍然未定义?

最佳答案

...when we use "running" variable in start method's if statement, does the value of "running" converted from being undefined(by default since it was not given a value) to true?

undefined是一个值:它强制为 false当用作 bool 值时,如 start 中所示。虚假值为 undefined , null , 0 , NaN , "" ,当然还有false 。所有其他值都是真实(包括 "0""false" ,这有时会让人感到惊讶)。

The second question, after if statement in start method why running was assigned to true.

因为if (running)的正文语句未运行,因为 if (running)是假的。

The third question, since running was assigned to true in start method Is its value changed globally as well?

只有一个running代码中的变量,它不是全局的,但可以被 Stopwatch 中的所有代码访问。函数(即使在 Stopwatch 返回之后)。所以设置它truestart意味着现在是true Stopwatch 中的整个代码。 ( stop 再次设置为 false。)

假设您刚刚创建了 Stopwatch 的实例。当您调用start时:

  1. if (running) throw...没有throw因为runningundefined ,这是假的。
  2. running = true;runningtruerunning 只有一份副本(每个 Stopwatch 实例)因此 Stopwatch 中的所有其他代码查看一个变量的当前值。
  3. startTime = new Date();将开始日期/时间保存在startTime中。喜欢running ,这些变量只有一个(每个 Stopwatch 实例)。

如果您随后调用start再次,if (running) throw...throw ,因为runningtrue现在。

稍后,如果您调用stop :

  1. if (!running) throw...没有throw因为runningtrue .
  2. running = false;runningfalse .
  3. endTime = new Date()endTime到当前日期/时间。
  4. const seconds = (endTime.getTime() - startTime.getTime()) / 1000;确定 start 之间的时间(以秒为单位)和stop被召唤了。
  5. duration += seconds添加secondsduration 中的现有值。 duration0 开始,但如果你这样做start/stop然后start/stop再次,它将记录两个计时器的总持续时间。

关于javascript - JS 中如何使用变量的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57132452/

相关文章:

javascript - 如何在javascript中减去2个字符以获得ascii的差异

javascript - UnhandledPromiseRejectionWarning : TypeError: res. 状态不是函数(NEXT JS)

javascript - 事件捕获与事件冒泡

javascript - Angularjs 自定义过滤器和依赖注入(inject)

javascript - 如何绕过 FormSpree 重定向?

javascript - 如何使用 Javascript/Jquery/HTML5 函数将 HTML 页面捕获为图像

javascript - 哪个更好 - Ext.get() 或 document.getElementById()

Javascript静态方法继承

javascript - Shopify 异步 Ajax 添加到购物车 - 部分工作?

javascript - Jquery,从下拉列表中删除选项不起作用