闭包
闭包可以让函数外部可以访问到函数内部的数据;
一个持有外部环境变量的函数就是闭包
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0,minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style>
body {
font-size: 12px;
}
h1 {
font-size: 1.5rem;
}
h2 {
font-size: 1.2rem;
}
</style>
</head>
<body>
<p>哈哈哈哈哈哈</p>
<h1>hhhhhhhhh</h1>
<h2>qqqqqqqqq</h2>
<a href="#" id="size-12">12</a>
<a href="#" id="size-14">14</a>
<a href="#" id="size-16">16</a>
<script>
//认识闭包
function fn() {
var a = 200;
function f1() {
var a = 100;
function f2() {
var a = 50;
return a;
}
return f2();
}
return f1();
}
var res = fn();
console.log(res);
//-------------------------闭包应用之一,setTimeout带参-------------------------------
var test = function(name) {
var name = '刘文博'
function getName() {
return console.log(name)
}
return getName()
}
setTimeout(test, 1000)
//-------------------------闭包应用之闭包应用场景之回调-------------------------------
function changeSize(size) {
return function() {
document.body.style.fontSize = size + 'px';
};
}
var size12 = changeSize(12);
var size14 = changeSize(14);
var size16 = changeSize(16);
document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;
//我们定义行为,然后把它关联到某个用户事件上(点击或者按键)。
//我们的代码通常会作为一个回调(事件触发时调用的函数)绑定到事件上
//-------------------------闭包应用场景之封装变量-------------------------------
//用闭包定义能访问私有函数和私有变量的公有函数。
var counter = (function() {
var privateCounter = 0; //私有变量
function change(val) {
privateCounter += val;
}
return {
increment: function() { //三个闭包共享一个词法环境
change(1);
},
decrement: function() {
change(-1);
},
value: function() {
return privateCounter;
}
};
})();
console.log(counter.value()); //0
counter.increment();
counter.increment(); //2
//共享的环境创建在一个匿名函数体内,立即执行。
//环境中有一个局部变量一个局部函数,通过匿名函数返回的对象的三个公共函数访问。
</script>
</body>
</html>