Var& JavaScript变量范围

时间:2013-02-07 17:29:00

标签: javascript html variables global-variables scope

JS代码

    var foo = "Hello World!"; // <------- global scope
    document.write("<p>Before our anonymous function foo means '" + foo + '".</p>');

    (function() {
        // The following code will be enclosed within an anonymous function
        var foo = "Goodbye World!"; // <------- local scope
        document.write("<p>Inside our anonymous function foo means '" + foo + '".</p>');
    })(); // We call our anonymous function immediately

    document.write("<p>After our anonymous function foo means '" + foo + '".</p>');

HTML输出

Before our anomymous function foo means 'Hello World!".

Inside our anomymous function foo means 'Goodbye World!".

After our anomymous function foo means 'Hello World!".

我的问题是

  • 当我们在函数内部替换foo变量的值时为什么 是不是取而代之?它如何仍然包含"Hello World!"
  • 如果我要访问函数内部的全局变量我该怎么办?

3 个答案:

答案 0 :(得分:3)

通过在函数中使用var foo,您明确告诉变量只能在该函数内进行本地更改。如果您想要全局更改,只需使用foo = ...

即可

如果您想阅读,我建议this SO Question

答案 1 :(得分:1)

从匿名函数中删除var语句,您将更改全局变量:

var foo = "Hello World!"; // <------- global scope
document.write("<p>Before our anonymous function foo means '" + foo + '".</p>');

(function() {
    // The following code will be enclosed within an anonymous function
    foo = "Goodbye World!"; // <------- local scope
    document.write("<p>Inside our anonymous function foo means '" + foo + '".</p>');
})(); // We call our anonymous function immediately

document.write("<p>After our anonymous function foo means '" + foo + '".</p>');

答案 2 :(得分:0)

您正在使用函数作用域变量来遮蔽全局变量。要访问全局变量,您可以使用window.foo

明确说明
var foo = "Hello World!"; // <------- global scope
document.write("<p>Before our anonymous function foo means '" + foo + '".</p>');

(function() {
    // The following code will be enclosed within an anonymous function
    var foo = "Goodbye World!"; // <------- local scope
    document.write("<p>Inside our anonymous function foo means '" + foo + '".</p>');
    document.write("<p>Inside our anonymous function window.foo means '" + window.foo + '".</p>');
    window.foo = window.foo + foo;
})(); // We call our anonymous function immediately

document.write("<p>After our anonymous function foo means '" + foo + '".</p>');

这将打印“Hello World!Goodbye World!”