Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the use of closures in JavaScript

Shulou Source: shulou.com Published: 2022-06-02 12:26:20 10月27日 Update

这篇文章主要介绍JavaScript中闭包有什么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

1. 什么是闭包

闭包:函数本身和该函数声明时所处的环境状态的组合。

也就是说函数不在其定义的环境中被调用,也能访问定义时所处环境的变量。

所以使用闭包,就可以将数据与操作该数据的函数相关联。

举个例子:

function foo() { let a = 1; return function() { console.log(a); }}let foo1 = foo();foo1() // 输出 1

这个就是一个闭包的例子,在 foo 中,由于 return 了一个函数,这个函数拥有涵盖 foo 内部作用域的闭包,也就是 a,使得 a 一直存活,不会在 foo 结束时被回收。

2. 闭包的作用2.1) 记忆性

什么是闭包的记忆性

当闭包产生时,函数所处环境的状态会始终保持在内存中,不会在外层函数调用结束后,被垃圾回收机制回收。

举个例子:

function foo() { let a = 0; return function() { a ++; console.log(a); }}let foo1 = foo();let foo2 = foo();foo1(); // 1foo2(); // 1foo2(); // 2foo1(); // 2

因为 a 属于闭包的一部分,所以当闭包产生时,a 所处的环境状态会保持在内存中,不会随外层函数调用结束后清除,所以随着 foo1的使用,a 都会在内存中的值加 1。

然后 foo1 和 foo2 产生的闭包是两个独立的闭包,它们互不影响。所以 foo2 第二次调用的时候,是在它自己第一次调用后结果上加 1.

2.2) 模拟私有变量

保证一个变量只能被进行指定操作。

举个例子:

function foo() { let A = 0; return { getA : function() { return A; }, add : function() { A ++; }, del : function() { A --; } }}let foo1 = foo();console.log(foo1.getA()); // 0foo1.add();console.log(foo1.getA()); // 1foo1.del();console.log(foo1.getA()); // 0

By closure, it is ensured that A can only be added or subtracted as specified.

3. Attention points of closure 

Closure cannot be abused, otherwise it may cause performance problems due to excessive memory consumption, and may even cause memory leaks.

The above is "What is the use of closures in JavaScript" all the content of this article, thank you for reading! Hope to share the content to help everyone, more relevant knowledge, welcome to pay attention to the industry information channel!

Tags: Closures functions memory environment examples variables states that is functions content data articles memory lifetime guarantee two that is value interest garbage Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology macOS vpn NVidia OPPO Reno