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!"
? - 如果我要访问函数内部的全局变量,我该怎么做?