嵌套的函数结构使setInterval函数不可见
Nested function structure make setInterval function unvisible
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);
}
相关文章:
- 可以't获取setInterval函数以使用javascript中的this.function_name调用另一
- 使用setInterval()函数进行图像闪烁
- 在setInterval函数之前声明时未定义对象
- 使用setInterval调用原型函数时出现问题
- setInterval函数不会更改视图中的$scope
- “单独列搜索”上的Datatables setinterval函数
- 如何使用setInterval执行函数
- setInterval可更改函数的背景
- Javascript setInterval 函数来清除自身
- setInterval调用具有未定义参数的函数
- setinterval函数,使用变量的前一个/旧值
- 如何在 setinterval 函数中访问 javascript 数组值
- 如何在 window.setInterval 中每分钟运行一次 getJSON 函数
- 在 jquery 移动中离开页面时结束 SetInterval 函数
- 我将如何在jQuery中切换setInterval函数的状态
- 在setInterval函数内部使用.call()传递参数
- Javascript 函数 setInterval() 只工作一次
- 哪一个最好在 jquery 中连续重复函数 setInterval 或回调函数
- 使用函数setinterval javascript错误使用函数
- 在同步函数中调用异步函数(setinterval)后返回值