嵌套的函数结构使setInterval函数不可见

Nested function structure make setInterval function unvisible

本文关键字:函数 setInterval 结构 嵌套      更新时间:2023-09-26

code1

<html>
<head>
<script type="text/javascript">
    function showTime(){
            var c=document.getElementById("text");
            var nowTime=new Date();
            c.innerHTML="time is  "+nowTime.toLocaleTimeString();
            }
    function startTime(){
        setInterval("showTime()",1000);
        }
</script>
</head>
<body onload="startTime()">
<div id="text"></div>
</body>
</html>

它运行成功,现在可以在startTime函数中嵌套showTime函数。

代码2

<html>
<head>
<script type="text/javascript">
    function startTime(){
        function showTime(){
            var c=document.getElementById("text");
            var nowTime=new Date();
            c.innerHTML="time is  "+nowTime.toLocaleTimeString();
        }
        setInterval("showTime()",1000);
    }
</script>
</head>
<body onload="startTime()">
<div id="text"></div>
</body>
</html>

出现错误,ReferenceError: showTime is not defined
1.对于code1,setInterval函数中双引号的作用是什么
2.对于code2,为什么showTime可以从startTime调用,比如在code1中?

我认为这可能是评估范围的问题。

function test() {
  var x = 2,
    y = 4;
  console.log(eval("x + y")); // Direct call, uses local scope, result is 6
  var geval = eval;
  console.log(geval("x + y")); // Indirect call, uses global scope, throws ReferenceError because `x` is undefined
}
test();

内部setInterval也使用eval来确定函数。因此,由于这种直接和间接调用的行为,它将抛出一个引用错误。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

"showTime()"是一个不可调用的字符串
正确的方法是:

 function startTime(){
        function showTime(){
            var c=document.getElementById("text");
            var nowTime=new Date();
            c.innerHTML="time is  "+nowTime.toLocaleTimeString();
        }
        setInterval(showTime,1000);
    }