JavaScript 全局变量不变

Posted

技术标签:

【中文标题】JavaScript 全局变量不变【英文标题】:JavaScript Global Variable Not Changing 【发布时间】:2022-01-01 14:02:15 【问题描述】:

我是 javascript 新手,我做了一个简单的秒表构造函数:

function Stopwatch() 
    var started = false;
    var elapsed;
    var start;
    d = new Date();
    this.duration = function() 
        if (started) 
            throw "Stopwatch is still running"
         else 
            return (elapsed);
        
    
    this.start = function() 
        if (started) 
            throw "Stopwatch has already started"; 
         else 
            start = d.getTime();
            started = true;
        
    
    this.stop = function() 
        if (!started) 
            throw "Stopwatch hasn't started";
         else 
            elapsed = d.getTime() - start;
            started = false;
        
    
    this.reset = function() 
        started = false;
        elapsed = 0;
    

let sw = new Stopwatch();
sw.start();

setTimeout(function () 
    sw.stop();
    console.log(sw.duration());
, 500);

错误的逻辑工作正常,但每当我调用 sw.duration() 时,它总是返回零,我不确定为什么会这样,因为我使用的是 var 而不是 let。请告诉我。

【问题讨论】:

你应该检查 ES6 类,因为这不是创建构造函数的理想方式。此外,没有理由混合使用varlet——只要有let 可用,就永远不要使用var。最后,隐式全局变量不好,所以请确保您处于严格模式。 【参考方案1】:

您只在构造函数开始时调用了一次new Date。改用Date.now(获取号码,避免调用.getTime),不仅在需要分配给start时调用,在.stop中调用,获取elapsed

function Stopwatch() 
    var started = false;
    var elapsed;
    var start;
    this.duration = function() 
        if (started) 
            throw "Stopwatch is still running"
         else 
            return (elapsed);
        
    
    this.start = function() 
        if (started) 
            throw "Stopwatch has already started"; 
         else 
            start = Date.now();
            started = true;
        
    
    this.stop = function() 
        if (!started) 
            throw "Stopwatch hasn't started";
         else 
            elapsed = Date.now() - start;
            started = false;
        
    
    this.reset = function() 
        started = false;
        elapsed = 0;
    

let sw = new Stopwatch();
sw.start();
setTimeout(() => 
  sw.stop();
  console.log(sw.duration());
, 500);

【讨论】:

以上是关于JavaScript 全局变量不变的主要内容,如果未能解决你的问题,请参考以下文章

React-Native - 全局变量不变

python函数中局部变量与全局变量遵守规则

[转自脚本之家] Javascript cookie 详解

如何使全局变量在多个 google appengine 实例上保持不变?

关于cookie的基础

JavaScript全局变量与局部变量