在 JavaScript 中,据说函数是使用定义函数时有效的作用域来执行的。它与调用函数时的有效范围无关。
这到底是什么意思?
下面的输出是 A,因为
foo
是在 function a
范围内定义的,所以它使用的变量
data
也是在
function a
范围内定义的变量。即使该函数在
function b
的范围内被 调用
(其中
data = "B"
),它也不会输出 B。
<div id="output"></div>
<script>
var data = "global";
function a() {
var data = "A";
function foo() {
document.getElementById('output').innerHTML = data;
}
return foo;
}
function b() {
var data = "B";
var func = a();
func();
}
b();
</script>
// Global variables are on every scope chain
var global = 'global'
// Function variables are only on a function's scope chain
function bar() {
var fn = 'fn';
// foo called from here where fn is avaialble as a local variable
foo(); // undefined
return function() {
alert(fn)
}
}
function foo() {
// foo can access global because it's on its scope chain
alert(global);
// Can't access fn because it's on bar's scope chain
// so returns undefined
alert(typeof fn);
}
// the function returned by bar has access to fn
var f = bar(); // global
f(); // fn