简体   繁体   English

JavaScript 中的局部变量和全局变量

[英]Local and global variables in JavaScript

Today, I started to code a page that prompts the user to choose their PC specification, and the code is as follows.今天开始编写一个页面,提示用户选择自己的PC规格,代码如下。

<html>
    <title>Computer Specification Chooser</title>

    <head>
        <script type="text/javascript">
            var compSpec = document.compChooser;

            function processorUnavailable_onclick()
            {
                alert("Sorry, that processor speed is currently unavailable.");
                compSpec.processor[2].checked = true;
            }
        </script>
    </head>

    <body>
        <form name="compChooser">
            <p>Tick all components you want included in your computer</p>

            <p>
            DVD-ROM

            <input type="checkbox" name="chkDVD" value="DVD-ROM" />
            <br />

            CD-ROM
            <input type="checkbox" name="chkCD" value="CD-ROM" />
            <br />

            Zip Drive
            <input type="checkbox" name="chkZIP" value="ZIP DRIVE" />
            </p>

            <p>
            Select the processor speed you require
            <br />

            <input type="radio" name="processor" value="3.8" />
            3.8 GHz

            <input type="radio" name="processor" value="4.8" onclick="processorUnavailable_onclick()" />
            4.8 GHz


            <input type="radio" name="processor" value="6" />
            6 GHz
            </p>

            <input type="button" name="btnCheck" value="Check Form" />
        </form>
    </body>

</html>

The problem I'm facing is in the function that I've tied to the event handler.我面临的问题是我绑定到事件处理程序的函数。 When I try to choose the radio button of the processor value 4.8 GHz, yes it alerts me with the message inside the function, but after that, it doesn't not execute the next statement inside the function, that is, to check the next processor value, 6 GHz.当我尝试选择处理器值为 4.8 GHz 的单选按钮时,是的,它用函数内部的消息提醒我,但之后,它不会执行函数内部的下一个语句,即检查下一个处理器值,6 GHz。

I've tried to change it and test on it, and found out when I set the var compSpec = document.compChooser as a local variable inside the function instead of a global variable, the next statement could be executed.我尝试更改它并对其进行测试,发现当我将var compSpec = document.compChooser为函数内部的局部变量而不是全局变量时,可以执行下一条语句。

But I thought for a global variable, it is accessible everywhere on the page and also inside a function.但我想到了一个全局变量,它可以在页面上的任何地方访问,也可以在函数内部访问。 But why now can't I accesses it inside my function?但是为什么现在我不能在我的函数中访问它?

Besides, I stumbled upon a weird article while googling.此外,我在谷歌搜索时偶然发现了一篇奇怪的文章。 It says that when a global variable is created, it is added to the window object.它说当一个全局变量被创建时,它被添加到window对象中。 Why does this happen?为什么会发生这种情况? And what are the benefits and uses of it?它有什么好处和用途?

In JavaScript, a global variable is a property of the global object.在 JavaScript 中,全局变量是全局对象的一个​​属性。 When running inside a browser, the global object is the window object.在浏览器中运行时,全局对象是window对象。 So if you don't use the var keyword, you are not actually declaring a variable, instead you are setting a property of the window object.因此,如果您不使用var关键字,您实际上并不是在声明变量,而是在设置window对象的属性。 It's useful because the window object is accessible from everywhere, and so is your global variable.它很有用,因为可以从任何地方访问window对象,您的全局变量也是如此。

If you declare compSpec as a variable ( var ) inside your processorUnavailable_onclick function, its scope will be limited to that function (and closures created inside it).如果您在processorUnavailable_onclick函数compSpec声明为变量( var ),则其作用域将仅限于该函数(以及在其中创建的闭包)。 If you set compSpec as a global variable (ie, a property of window ), then it will be available from everywhere:如果您将compSpec设置为全局变量(即window的属性),则它可以从任何地方使用:

function body_onload()
{
    window.compSpec = document.compChooser;
}

function processorUnavailable_onclick()
{
    alert("Sorry, that processor speed is currently unavailable.");
    window.compSpec.processor[2].checked = true;
}

...<body onload="body_onload()">...

Your problem is this line: compSpec = document.compChooser你的问题是这一行: compSpec = document.compChooser

When this code runs, the form is not yet part of the DOM, so compSpec is undefined.当这段代码运行时,表单还不是 DOM 的一部分,所以compSpec是未定义的。

Place your code at the end of the document or run it in an onload handler and it will work.将您的代码放在文档的末尾或在 onload 处理程序中运行它,它将起作用。

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

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