揭秘 JS 中的闭包
文章标签
JS
const securebooking = function(){ let passengercount = 0; return function(){ passengercount++; console.log(`${passengercount} passengers`); }}const booker = securebooking();booker();booker();booker();
概括
let f;const g = function(){ const a = 23; f = function() { console.log(a*2); // 46 };};const h = function(){ const b = 777; f = function(){ console.log(b*2); // 1554 };};g();f();console.dir(f);// f fn is reassigned using h fn. hence, old closure value i.e 'a' will be replaced with new value 'b' which can be verified using console.dir().h();f();console.dir(f);
// Boarding Passengers using Closuresconst boardPassengers = function(n, wait){ const perGroup = n / 3; setTimeout(function(){ console.log(`We are now boarding all ${n} passengers`); console.log(`There are 3 groups, each with ${perGroup} passengers`) }, wait*1000); console.log(`Will start boarding in ${wait} seconds`);}boardPassengers(180, 3);