闭包
闭包的概念: 函数A中, 有一个函数B, 函数B中可以访问函数A中定义的变量或者是数据, 此时形成了闭包(这句话暂时不严谨)
- 闭包的模式: 函数模式的闭包, 对象模式的闭包
- 闭包的作用: 缓存数据, 延长作用域链
- 闭包的优点和缺点: 缓存数据
- 闭包的应用
函数模式的闭包: 在一个函数中有一个函数
//函数模式的闭包:在一个函数中有一个函数
function f1() {
var num = 10;
//函数的声明
function f2() {
console.log(num);
}
//函数调用
f2();
}
f1();
function f1() {
var num = 10;
return function () {
console.log(num); //10
return num;
}
}
var ff = f1();
var result = ff();
console.log(result); //10
对象模式的闭包:函数中有一个对象
function f3() {
var num = 10;
var obj = {
age: num
};
console.log(obj.age);//10
}
f3();
function f2() {
var num = 100;
return {
age: num
}
}
var obj = f2();
console.log(obj.age);
来源:https://www.cnblogs.com/jane-panyiyun/p/12172828.html