在 Javascript 中,据说函数是使用定义函数时有效的范围执行的。它与调用函数时的作用域无关。
它到底是什么意思?有人可以用简单的例子解释一下。
下面的输出是 A 因为foo
是在 的范围内定义的,所以它使用function a
的变量也是在 的范围内定义的变量。data
function a
即使在where范围内调用了该函数,它也不输出 B 。function b
data = "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