函数的作用域是在声明时确定的,而不是在执行时确定的。
var a = 1;
var b = 2;
var b = 3;
function foo(fn){
//JS is function-scoped. It's the only way you can create a new scope.
//This is a new scope. It cannot be accessed from the outside
var a = 4;
var b = 5;
var b = 6;
//We call the passed function. Unless we pass it some references from this scope
//the function can never touch anything inside this scope
fn('hello world');
}
foo(function(hw,obj){
//the function passed is defined here where, one scope out, is the global scope
//which is also where a, b and c are defined. I can *see* them, thus they are
//modifiable
console.log(a,b,c); //123
a = 7;
b = 8;
c = 9;
console.log(a,b,c); //789
console.log(hw); //hello world
});
此外,全局变量在代码中的任何位置都可见。任何代码都可以修改全局变量,除了某些情况,比如 WebWorkers,但那是另一回事了。
这是一个如何使用即时函数隐藏值的示例,并且只公开函数以使用它们:
(function(ns){
var width = 320;
var height = 240;
ns.getArea = function(fn){
fn.call(null,320 * 240);
}
}(this.ns = this.ns || {}));
//let's get the area
ns.getArea(function(area){
console.log(area);
});
//In this example, we have no way to modify width and height since it lives inside
//a scope that we can't access. It's modifiable only from within the scope
//or using a "setter" approach like in classical OOP
但是对于对象,它们是通过引用传递的。一旦你将它们传递到某个地方,它们可能会被修改。