在Javascript中,据说函数是使用定义函数时有效的作用域执行的。它与调用函数时生效的作用域无关。
这到底是什么意思?有人能用简单的例子来解释一下吗?
发布于 2013-03-15 20:31:17
下面的输出是A,因为foo是在function a作用域中定义的,所以它使用的变量data也是在function a作用域中定义的变量。
即使函数是在function b where 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>发布于 2013-03-15 20:37:09
// 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(); // fnhttps://stackoverflow.com/questions/15432443
复制相似问题