->在任何地方都可以调用内部函数
->内部函数能访问外部变量
i:
var globalVar;
function outerFn() {
console.log('Outer function');
function innerFn() {
console.log('Inner function');
}
globalVar = innerFn;
}
console.log('outerFn():');
outerFn();
console.log('globalVar():');
globalVar();
ii:
function outerFn() {
console.log('Outer function');
function innerFn() {
console.log('Inner function');
}
return innerFn;
}
console.log('var fnRef = outerFn():');
var fnRef = outerFn();
console.log('fnRef():');
fnRef();
iii:
function outerFn() {
function innerFn() {
var innerVar = 0;
innerVar++;
console.log('innerVar = ' + innerVar);
}
return innerFn;
}
var fnRef = outerFn();
fnRef();
fnRef();
var fnRef2 = outerFn();
fnRef2();
fnRef2();
当内部函数在定义它作用域的外部被引用时,就创建了改内部函数的一个闭包。