我不明白范围是什么。我在某处读过范围是访问变量的方式。但是我发现很难想出一个变量可以通过范围访问的情况。函数内的所有变量都可以通过“全局”或“激活/变量”对象的上下文或通过闭包来访问。这是一段代码来演示我的意思:
var global_var = 7;
var f = (function() {
var closure_var = 5;
return function() {
var local_var = 3;
alert(local_var); // alerts 3 - visible through context as Activation Object's property
alert(closure_var); // alerts 5 - visible through closure
alert(global_var); // alerts 7 - visible through context as Global Object's property
alert(this.global_var); // alerts 7 - visible through context as Global Object's property
}
})();
f();
那么什么是作用域?这是这里的摘录和我的评论:
// a globally-scoped variable
var a=1;
// global scope
function one(){
alert(a);
}
// no, it's accessible as global object's context
// local scope
function two(a){
alert(a);
}
// no, it's accessible as activation object's context
编辑:
谢谢大家。我想我必须从变量和函数的角度来看范围。