javaScript闭包:
闭包就是能够读取其他函数内部 变量的函数,由于在js语言中,只有函数内部的子函数才能读取局部变量。因此可以把闭包简单的理解成定义在一个函数内部的函数.所以,在本质上,闭包就是将函数内部和函数外部连接起来的一座桥梁.
什么是闭包:
闭包的模式: 函数模式的闭包 对象模式的闭包
闭包的作用: 缓存数据, 延长作用域
闭包的优点和缺点: 缓存数据(有缓存 把数据存下来 可以继续用 但是如果你一直不释放这个数据 最终内存会爆掉)
函数模式的闭包:
function fn() {
var num = 10;
return function () {
return num;
}
fn2();
}
var ff = fn();
console.log(ff());
对象模式的闭包:
function fn() {
var num = 10;
return {
age: num
}
}
var obj = fn();
console.log(obj.age);
=============================================>
使用闭包 产生多个相同的随机数
思路: 把 生成的随机数缓存下来 一致调用输出
function fn() {
var num = Math.floor(Math.random() * 10 + 1);
return function () {
return num;
}
}
var res = fn(); // 7
console.log(res());
console.log(res());
console.log(res());