仅在函数外部起作用的javascript代码

编程入门 行业动态 更新时间:2024-10-09 16:27:25
本文介绍了仅在函数外部起作用的javascript代码-为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

为什么这段代码不能像下面的代码那样工作,但是如果我注释掉 function testBgChange(){函数并将代码保留在该函数中,它将可以正常工作.如果我将代码保留在函数中,然后调用该函数,会有什么区别?

How come this code does not work as its written below but if I comment out function testBgChange(){ and keep the code inside that function it works fine. What difference does it make if I keep the code within the function and then call that function?

<html> <head> <script type="text/javascript"> testBgChange(); function testBgChange(){ var i = 0; var c = 0; var time = 3000; var incr = 3000; while(i<=3){ if(c==0){ var red = "#FF0000"; setTimeout("changeBgColor(red)",time); time+=incr; c=1; } else if(c==1){ var white = "#FFFFFF"; setTimeout("changeBgColor(white)",time); time+=incr; c=0; } i+=1; } } function changeBgColor(color){ document.getElementById("alert").style.backgroundColor = color; } </script> </head> <body> <p id="alert"> <br> <br> Testing <br> <br> </p> </body> </html>

推荐答案

由于在函数中声明 var red 和 var white 时,只能从内部访问功能.这是一个问题,因为 setTimeout 将在全局范围内调用 eval ,而该全局范围无法访问这些变量.

Because var red and var white, when declared inside the function, can only be accessed from within the function. This is a problem becausesetTimeout will call eval in the global scope, which does not have access to these variables.

有多种方法可以解决此问题,但是最好给 setTimeout 一个函数而不是字符串.当新函数创建一个 closure 并保留对包含函数中变量的访问权限时,这将解决您的问题:

There are a variety of ways to work around this, but it's better practice to give setTimeout a function rather than a string. This will solve your problem as the new function creates a closure that retains access to the variables in the containing function:

var red = "#FF00000"; setTimeout(function () { changeBgColor(red); }, time);

更多推荐

仅在函数外部起作用的javascript代码

本文发布于:2023-11-27 21:23:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639653.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   代码   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!