函數的作用域在聲明時確定,而不是在執行時確定。
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
但對於對象,它們是通過引用傳遞。一旦你將它們傳遞到某個地方,它們可能會修改。
您傳入的函數已經有了不同的範圍,您不會對外部函數做任何更改...您可以發佈一些代碼,也許我沒有想到... – elclanrs 2013-05-07 09:00:01
什麼是你的意思是受保護? – 2013-05-07 09:02:31
現在檢查。我已經添加了一個例子和我的意圖。 – 2013-05-07 09:14:37