JavaScript允许你引用在当前函数以外定义的变量。
// 内部的make函数引用了定义在外部makeSandwich函数内的magicIngredient变量。
function makeSandwich(){
var magicIngredient = "peanut butter";
function make(filling){
return magicIngredient + " and " + filling;
}
return make("jelly");
}
makeSandwich(); // "peanut butter and jelly"
即使外部函数已经返回,当前函数仍然可以引用在外部函数所定义的变量。
// 即使sandwichMaker函数已经返回,make函数仍能记住magicIngredient的值。
function sandwichMaker(){
var magicIngredient = "peanut butter";
function make(filling){
return magicIngredient + " and " + filling;
}
return make;
}
var f = sandwichMaker();
f("jelly"); // "peanut butter and jelly"
f("bananas"); // "peanut butter and bananas"
f("marshmallows"); // "peanut butter and marshmallows"
函数可以引用在其作用域内的任何变量,包括参数和外部函数变量。
function sandwichMaker(magicIngredient){
function make(filling){
return magicIngredient + " and " + filling;
}
return make;
}
var hamAnd = sandwichMaker("ham");
hamAnd("cheese"); // "ham and cheese"
hamAnd("mustard"); // "ham and mustard"
var turkeyAnd = sandwichMaker("turkey");
turkeyAnd("Swiss"); // "turkey and Swiss"
turkeyAnd("Provolone"); // "turkey and Provolone"
使用函数表达式构建闭包
function sandwichMaker(magicIngredient) {
return function(filling) {
return magicIngredient + " and " + filling;
};
}
闭包可以更新外部变量的值
function box() {
var val = undefined ;
return {
set: function(newVal) { val = newVal; },
get: function() { return val; },
type: function() { return typeof val }
};
}
var b = box();
b.type(); // "undefined"
b.set(98.6);
b.get(); // 98.6
b.type(); // "number"
// 通过set闭包更新val的值,随后调用get和type查看更新的结果。
提示
- 函数可以引用定义在其外部作用域的变量。
- 闭包比创建它们的函数有更长的生命周期。
- 闭包在内部存储其外部变量的引用,并能读取这些变量。