您可以这样做以实现类似的作用域,但只创建一个副本fn2
:
//Initiliaze before you call `fn1`:
var fn1 = (function(){
// This is the function assigned to fn1
return function(){
fn2();
}
function fn2()
{
//Stuff happens here
}
})();
将这些控制台输出与 fiddles 进行比较,前者创建一个额外的副本,因为每次调用都会创建fn2
一个本地范围:http : //jsfiddle.net/A2UvC/3/和http://jsfiddle.net /A2UvC/3/fn2
fn1
然而,额外的副本也有优势fn2
。他们可能可以访问不同的变量,例如在以下情况下:
function fn1(x){
// Return an object exposing fn2 to the caller's scope
return {fn2: fn2};
// Each call to fn1 creates a new fn2 which has access
// to the closured `x` from the call to fn1 that created it
function fn2(){
console.log(x);
}
}
var ex1 = fn1(1);
var ex2 = fn1(2);
ex1.fn2 == ex1.fn2; // true
ex1.fn2 == ex2.fn2; // false, because they are two distinct copies
ex1.fn2(); // 1
ex2.fn2(); // 2
ex2.fn2(); // 2
ex1.fn2(); // 1