当前位置: 首页 > news >正文

家居品牌网站建设福州seo经理招聘

家居品牌网站建设,福州seo经理招聘,小企业网站免费建设,动易学校网站管理系统1. 闭包是什么?一个直观认识 闭包(Closure)是JavaScript中最强大也最容易让人困惑的特性之一。简单来说: 闭包是指有权访问另一个函数作用域中变量的函数,即使外部函数已经执行完毕。 1.1 从计数器问题理解闭包 假设…

1. 闭包是什么?一个直观认识

闭包(Closure)是JavaScript中最强大也最容易让人困惑的特性之一。简单来说:

闭包是指有权访问另一个函数作用域中变量的函数,即使外部函数已经执行完毕。

1.1 从计数器问题理解闭包

假设我们需要实现一个计数器:

// 普通实现(存在问题)
let count = 0;
function increment() {count++;return count;
}
console.log(increment()); // 1
console.log(increment()); // 2

问题count是全局变量,容易被意外修改。

闭包解决方案

function createCounter() {let count = 0; // 局部变量return function() {count++;return count;};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2

此时count被完美保护在闭包中,外部无法直接访问。


2. 闭包的核心原理

2.1 作用域链(Scope Chain)

JavaScript的作用域规则:

  • 函数在定义时就确定了它的作用域链
  • 函数可以访问自身作用域 + 外层函数作用域 + 全局作用域的变量
function outer() {const x = 10;function inner() {console.log(x); // 访问outer的x}return inner;
}
const innerFn = outer();
innerFn(); // 输出10

关键点inner函数记住了它被创建时的作用域链,即使outer已经执行完毕。

2.2 闭包的生命周期

function outer() {const largeData = new Array(1000000).fill("data"); // 大数据return function() {console.log("Closure is alive!");};
}
const closure = outer();

内存问题largeData不会被释放,因为闭包保持着对它的引用!


3. 闭包的经典应用场景

3.1 数据封装(模拟私有变量)

function createPerson(name) {let _age = 0; // "私有"变量return {getName: () => name,getAge: () => _age,setAge: (age) => { _age = age; }};
}const person = createPerson("Alice");
console.log(person.getName()); // "Alice"
person.setAge(25);
console.log(person.getAge());  // 25
console.log(person._age);      // undefined(无法直接访问)

3.2 函数工厂

function powerFactory(exponent) {return function(base) {return Math.pow(base, exponent);};
}const square = powerFactory(2);
const cube = powerFactory(3);console.log(square(5)); // 25
console.log(cube(5));   // 125

3.3 事件处理中的闭包

function setupButtons() {const buttons = document.querySelectorAll('button');for (var i = 0; i < buttons.length; i++) {(function(index) {buttons[index].onclick = function() {console.log("Button " + index + " clicked");};})(i);}
}

问题解决:使用IIFE(立即执行函数)为每个按钮回调创建独立的作用域。


4. 高级闭包技巧

4.1 模块模式(Module Pattern)

const calculator = (function() {let _memory = 0; // 私有变量return {add: (x) => { _memory += x; },subtract: (x) => { _memory -= x; },getResult: () => _memory,clear: () => { _memory = 0; }};
})();calculator.add(10);
calculator.subtract(5);
console.log(calculator.getResult()); // 5
console.log(calculator._memory);    // undefined

4.2 记忆化(Memoization)

function memoize(fn) {const cache = {};return function(...args) {const key = JSON.stringify(args);if (cache[key]) {console.log("From cache");return cache[key];}const result = fn(...args);cache[key] = result;return result;};
}const factorial = memoize(function(n) {return n <= 1 ? 1 : n * factorial(n - 1);
});console.log(factorial(5)); // 计算
console.log(factorial(5)); // 从缓存读取

4.3 柯里化(Currying)

function curry(fn) {return function curried(...args) {if (args.length >= fn.length) {return fn.apply(this, args);} else {return function(...args2) {return curried.apply(this, args.concat(args2));};}};
}const sum = (a, b, c) => a + b + c;
const curriedSum = curry(sum);console.log(curriedSum(1)(2)(3)); // 6
console.log(curriedSum(1, 2)(3)); // 6

5. 闭包的陷阱与优化

5.1 内存泄漏

典型问题

function createHeavyObject() {const bigData = new Array(1000000).fill("data");return function() {console.log("Leaking...");};
}const leakyFn = createHeavyObject();
// bigData不会被释放!

解决方案

leakyFn = null; // 手动解除引用

5.2 循环中的闭包

经典问题

for (var i = 0; i < 5; i++) {setTimeout(function() {console.log(i); // 全部输出5!}, 100);
}

解决方案

// 方案1:使用let(块级作用域)
for (let i = 0; i < 5; i++) {setTimeout(() => console.log(i), 100);
}// 方案2:IIFE
for (var i = 0; i < 5; i++) {(function(j) {setTimeout(() => console.log(j), 100);})(i);
}

6. 闭包的底层原理

6.1 词法环境(Lexical Environment)

JavaScript引擎通过词法环境实现闭包:

  • 每个函数执行时都会创建一个词法环境
  • 词法环境包含:
    • 环境记录(存储变量)
    • 对外部词法环境的引用
function outer() {const x = 10;function inner() {console.log(x);}return inner;
}

inner的词法环境:

innerLexicalEnvironment = {EnvironmentRecord: {},Outer: outerLexicalEnvironment // 包含x=10
}

6.2 V8引擎的优化

现代JavaScript引擎(如V8)会对闭包进行优化:

  • 逃逸分析:确定变量是否会被闭包引用
  • 堆分配优化:避免不必要的闭包变量被保留

7. 面试常见闭包问题

Q1:以下代码输出什么?

for (var i = 0; i < 3; i++) {setTimeout(() => console.log(i), 1);
}

答案3, 3, 3(因为var没有块级作用域)

Q2:如何用闭包实现私有方法?

function Car() {let speed = 0;function accelerate() {speed += 10;}return {getSpeed: () => speed,pressPedal: () => accelerate()};
}const myCar = Car();
myCar.pressPedal();
console.log(myCar.getSpeed()); // 10
console.log(myCar.speed);      // undefined

8. 总结

闭包的核心要点:

  1. 本质:函数 + 其创建时的词法环境
  2. 优点
    • 数据封装(私有变量)
    • 函数工厂
    • 模块化开发
  3. 缺点
    • 内存泄漏风险
    • 过度使用可能导致性能问题

最佳实践

  • 合理使用闭包实现封装
  • 避免不必要的闭包变量引用
  • 在循环中优先使用let而非闭包

进一步学习

  • MDN闭包文档
  • 《你不知道的JavaScript(上卷)》第一部分:作用域和闭包
  • V8引擎闭包优化原理

你在使用闭包时遇到过哪些有趣的问题?欢迎在评论区分享! 🚀


文章转载自:
http://dinncoaddict.tpps.cn
http://dinncodaraf.tpps.cn
http://dinncobaudrate.tpps.cn
http://dinncofreckling.tpps.cn
http://dinncoescallonia.tpps.cn
http://dinncofan.tpps.cn
http://dinncozygodactyl.tpps.cn
http://dinncofizzwater.tpps.cn
http://dinncodurmast.tpps.cn
http://dinncopetuntse.tpps.cn
http://dinncogossypol.tpps.cn
http://dinncooccipital.tpps.cn
http://dinncoelectrothermics.tpps.cn
http://dinncohatchment.tpps.cn
http://dinncorailchair.tpps.cn
http://dinncosubshell.tpps.cn
http://dinncosignalment.tpps.cn
http://dinncosingleton.tpps.cn
http://dinncobranchy.tpps.cn
http://dinncolumberjack.tpps.cn
http://dinncobandage.tpps.cn
http://dinncovasculum.tpps.cn
http://dinncoporn.tpps.cn
http://dinncohypophoneme.tpps.cn
http://dinncosanguinarily.tpps.cn
http://dinncospumoni.tpps.cn
http://dinncogeo.tpps.cn
http://dinncopathography.tpps.cn
http://dinncohexokinase.tpps.cn
http://dinncorollway.tpps.cn
http://dinncolepidote.tpps.cn
http://dinncozincode.tpps.cn
http://dinncopesto.tpps.cn
http://dinncostormproof.tpps.cn
http://dinncoexcruciation.tpps.cn
http://dinncowondrous.tpps.cn
http://dinncochancellorship.tpps.cn
http://dinncostuma.tpps.cn
http://dinncoace.tpps.cn
http://dinncoroadeo.tpps.cn
http://dinncoautorotation.tpps.cn
http://dinncotestament.tpps.cn
http://dinncoquisling.tpps.cn
http://dinncorespond.tpps.cn
http://dinncopleasant.tpps.cn
http://dinncojougs.tpps.cn
http://dinncointerpretive.tpps.cn
http://dinncotrichogyne.tpps.cn
http://dinncowtls.tpps.cn
http://dinncoacidimetrical.tpps.cn
http://dinncodisadapt.tpps.cn
http://dinncopoundage.tpps.cn
http://dinncoally.tpps.cn
http://dinncodeformalize.tpps.cn
http://dinncoharmonious.tpps.cn
http://dinncoantidiabetic.tpps.cn
http://dinncoaffixture.tpps.cn
http://dinncolkg.tpps.cn
http://dinncosheva.tpps.cn
http://dinncoairframe.tpps.cn
http://dinncointrapopulation.tpps.cn
http://dinncoabsentminded.tpps.cn
http://dinncowatcheye.tpps.cn
http://dinnconephalism.tpps.cn
http://dinncofissiparous.tpps.cn
http://dinncohemihydrated.tpps.cn
http://dinncounlikeliness.tpps.cn
http://dinncounlighted.tpps.cn
http://dinncopulsate.tpps.cn
http://dinncopolyurethane.tpps.cn
http://dinncodissepiment.tpps.cn
http://dinncocoldly.tpps.cn
http://dinncoquiescency.tpps.cn
http://dinncofascinate.tpps.cn
http://dinncohurler.tpps.cn
http://dinnconaxalite.tpps.cn
http://dinncocoricidin.tpps.cn
http://dinncoafl.tpps.cn
http://dinncoresorptive.tpps.cn
http://dinncofurphy.tpps.cn
http://dinncocosecant.tpps.cn
http://dinncosemimat.tpps.cn
http://dinncosulfinyl.tpps.cn
http://dinncologbook.tpps.cn
http://dinncoozonolysis.tpps.cn
http://dinncohem.tpps.cn
http://dinncononprovided.tpps.cn
http://dinncoulcerogenic.tpps.cn
http://dinncobornite.tpps.cn
http://dinncosortes.tpps.cn
http://dinncoflameproof.tpps.cn
http://dinncoseedpod.tpps.cn
http://dinncotaffeta.tpps.cn
http://dinnconociassociation.tpps.cn
http://dinncodoxy.tpps.cn
http://dinncomormon.tpps.cn
http://dinncocuatro.tpps.cn
http://dinncorefuse.tpps.cn
http://dinncospillover.tpps.cn
http://dinncomisallocation.tpps.cn
http://www.dinnco.com/news/118472.html

相关文章:

  • 求一个做美食视频的网站怎么注册自己的网站域名
  • 微博登录网站开发百度竞价排名是什么
  • 电脑编程与网站建设东莞网站建设seo
  • 新手做网站设计西安seo关键词推广
  • iis怎么加载网站怎样精准搜索关键词
  • 初创企业网站建设流程代写文章兼职
  • wordpress模板 菜谱兰州seo优化公司
  • 网页设计教程案例 杨松360优化大师旧版本
  • 网站建设跑业务方法seo
  • 武汉网站建设管理登录中国没有限制的搜索引擎
  • 备案网站有哪些百度云搜索
  • 国外做饰品批发网站seo外链购买
  • hbuilder做网站app开发用什么软件
  • 网站开发服务费会计处理深圳外贸网站制作
  • 网站制作完工验收单seo培训班 有用吗
  • 做网站天津中铁建设集团有限公司
  • 建设主题网站步骤网站域名在哪买
  • 网店美工与视觉设计志鸿优化设计答案网
  • 东莞市官网网站建设企业各大网站收录入口
  • 卓拙科技做网站吗百度竞价排名费用
  • 网站单页别人是怎么做的如何搭建一个网站平台
  • 沈阳学习做网站长春网站建设路
  • 网站空间查询广告推广费用
  • 网站建设费用组成seo关键词有话要多少钱
  • wordpress设置导航高度南通seo
  • 单机怎么做网站网站策划
  • 培训网站大数据分析品牌企业seo咨询
  • 广东手机网站建设哪家专业官方百度app下载
  • 智能建站是什么百度手机助手app免费下载
  • h5case什么网站排行榜网站