仅在函数外部起作用的javascript代码-为什么? [英] javascript code that only works outside of a function - why?

查看:50
本文介绍了仅在函数外部起作用的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代码-为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆