我是 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
返回之后)。所以设置它true
在start
意味着现在是true
Stopwatch
中的整个代码。 ( stop
再次设置为 false
。)
假设您刚刚创建了 Stopwatch
的实例。当您调用start
时:
-
if (running) throw...
没有throw
因为running
是undefined
,这是假的。 -
running = true;
套running
至true
。running
只有一份副本(每个Stopwatch
实例)因此Stopwatch
中的所有其他代码查看一个变量的当前值。 -
startTime = new Date();
将开始日期/时间保存在startTime
中。喜欢running
,这些变量只有一个(每个Stopwatch
实例)。
如果您随后调用start
再次,if (running) throw...
会throw
,因为running
是 true
现在。
稍后,如果您调用stop
:
-
if (!running) throw...
没有throw
因为running
是true
. -
running = false;
套running
至false
. -
endTime = new Date()
套endTime
到当前日期/时间。 -
const seconds = (endTime.getTime() - startTime.getTime()) / 1000;
确定start
之间的时间(以秒为单位)和stop
被召唤了。 -
duration += seconds
添加seconds
到duration
中的现有值。duration
从0
开始,但如果你这样做start
/stop
然后start
/stop
再次,它将记录两个计时器的总持续时间。
关于javascript - JS 中如何使用变量的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57132452/