闭包closure现象指的是:有权访问另一个函数作用域中的变量 的函数
闭包的主要作用:延伸了变量的作用范围
闭包的缺点:内存泄漏
被访问的局部变量所在的函数fn 叫做闭包函数
<script>
// 闭包应用-计算打车价格
// 打车起步价14(3公里内),之后每多一公里增加5块钱. 用户输入公里数(n),就可以计算打车价格
// 如果有拥堵情况,总价格多收取10块钱拥堵费
// function fn() {}
// fn()
// 立即执行
// n:公里数
// 闭包现象:price、yd两个函数访问了匿名函数的局部变量start、total、
// 闭包函数:变量所在的这个匿名函数
let car = (function () {
let start = 14;
let total = 0;
let i = 0;
return {
// 正常价格
price: function (n) {
if (n <= 3) {
total = start;
} else {
total = start + (n - 3) * 5;
}
return total;
},
// 拥堵价格
yd: function (flag) {
return flag ? total + 10 : total;
},
};
})();
// car.price(5); // n=5公里数
console.log(car.price(5)); // 24
car.yd(true);
console.log(car.yd(true)); // 拥堵34
console.log(car.price(1)); // 起步价14
car.yd(false);
console.log(car.yd(false)); // 不拥堵14
// return里的函数返回给car
// car =
// {
// price: function () {
// if (n <= 3) {
// total = start;
// } else {
// total = start + (n - 3) * 5;
// }
// return total;
// },
// yd: function () {},
// };
// return total 返回给了car.price() 和car.yd()
// total = car.price(5)
// total = car.yd()
</script>