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!"
- 如果我要访问函数中的全局变量,我该怎么做
通过在函数中使用var foo
,您明确地告诉变量只在该函数中进行局部更改。如果你想在全球范围内更改它,只需使用foo = ...
如果你想读一读,我建议这个SO问题
从匿名函数中删除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>');
您正在使用函数范围的变量来隐藏全局变量。要访问全局变量,您可以使用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!"