简体   繁体   English

通用全局变量和对象(作为JavaScript中的变量)之间的混淆

[英]Confusion between a general global variable and object as a variable in javaScript

Below is my code. 下面是我的代码。 When I'm calling myDate variable outside of myTime() function to create a Date() object, the setInterval() function don't fire but when it's inside myTime() function. 当我在myTime()函数外部调用myDate变量以创建Date()对象时, setInterval()函数不会触发,而是在myTime()函数内部时myTime() As I know myDate variable is a global variable and it should work same inside or outside of the function. 据我所知, myDate变量是一个全局变量,它在函数内部或外部应该相同。 But why here the setInterval() method not firing while I'm creating the Date() object outside of the function? 但是,为什么在我在函数外部创建Date()对象时, setInterval()方法没有触发? Experts explain the things. 专家解释这些事情。 TIA TIA

var myDate = new Date();
    function myTime(){
        document.getElementById('text').innerHTML = myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds();
    }
    setInterval(myTime, 1000);

You are right: myDate variable is accessible from myTime() function, but if it is declared outside of it, its value doesn't change. 没错: myDate变量可从myTime()函数访问,但是如果在变量外部声明,则其值不会更改。 In the following snippet i've created one more external variable i to show that it is accessible from within the function: 在以下代码段中,我创建了另一个外部变量i以表明可以从函数内部对其进行访问:

 var myDate = new Date(); var i = 0; function myTime() { document.getElementById('text').innerHTML = myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds() + " (" + i++ + ")"; } setInterval(myTime, 1000); 
 <div id="text"></div> 

On the other hand, if you declare myDate variable inside the function, it will be created each time function is called - every second: 另一方面,如果在函数内部声明myDate变量,则每次调用函数时都会创建该变量-每秒:

 function myTime() { var myDate = new Date(); document.getElementById('text').innerHTML = myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds(); } setInterval(myTime, 1000); 
 <div id="text"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM