Does es6 have closures?
es6 has closures. In es6, when you create another function inside a function, the embedded function is called a closure, which can access the local variables of the external function; simply put, a closure refers to a function that has the right to access variables in the scope of another function. function. The main function of closures is to extend the scope of variables. Since closures will cause the variables in the function to be stored in memory, which consumes a lot of memory, closures cannot be abused, otherwise it will cause performance problems on the web page, and may lead to memory leaks in IE.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
1. Variable Scope
Variables are divided into two types according to their scope: global variables and local variables.
Global variables can be used inside functions.
Local variables cannot be used outside the function.
When the function completes execution, the local variables in this scope will be destroyed.
2. What is closure?
In es6, closure refers to a function that has access to variables in the scope of another function. Simple understanding: a scope can access local variables inside another function.
Closure: Create another function inside a function. The embedded function is called a closure. It can access the local variables of the external function
// fun 这个函数作用域 访问了另外一个函数 fn 里面的局部变量 num function fn(){ let num = 10 function fun(){ console.log(num) } fun() } fn() //10
The main point of closure Function: Extends the scope of variables.
// fn 外面的作用域可以访问fn 内部的局部变量 function fn(){ let num = 10 // 方法一: 先定义再返回函数 function fun(){ console.log(num) } return fun //返回 fun函数 } let f = fn() f() //10
// fn 外面的作用域可以访问fn 内部的局部变量 function fn(){ let num = 10 // 方法二: 直接返回函数 return function(){ console.log(num) } } let f = fn() f() //10
3. Usage scenarios of closures
(1) Used to return values
//以闭包的形式将 name 返回 function fun(){ let name = 'woniu' //定义闭包 return function f1(){ return name } } let ft = fun() //因为fun函数的返回值是f1函数,ft实质是一个函数 let na = ft() //调用ft函数,实际调用的就是f1函数 console.log(na); //woniu
(2) Function assignment: Define function expression inside the function
var f2 function fn(){ let name = '曹操' f2 = function(){ //闭包,将外部函数的name变量作为闭包的返回值 return name } } fn() //必须先调用fn函数,否则f2不是一个函数 console.log(f2()); //曹操
(3) Use closure as parameter of function
function fn(){ let name = '蜗牛学苑' //定义闭包 return function callback(){ return name } } let f1 = fn() //将fn函数的返回值callback赋给f1 function f2(temp){ console.log(temp()) //输出temp函数的返回值,实际调用了闭包callback } //调用f2函数:将f1作为实参传递给temp f2(f1)
(4) Use closures in immediate execution functions
//立即执行函数 (function(){ let name = '蜗牛学苑' let f1 = function(){ return name } fn2(f1) //调用fn2函数,将闭包f1作为实参传递给fn2函数 })() function fn2(temp){ //temp是一个形参,接收f1 console.log(temp()); //对temp的调用,实际调用的是闭包f1 }
(5) Loop assignment
(function(){ for (let i = 1; i <= 10; i++) { ( function(j){ setTimeout(function(){ console.log(j); },j*1000) } )(i) } })()
(6) Encapsulate closures in In the object,
function fun(){ let name = '蜗牛学苑' setName = function(na){ //setName是闭包,用来设置外部函数的变量值 name = na } getName = function(){ //getName是闭包,用来返回外部函数的变量值 return name } //外部fun函数的返回值,将闭包封装到对象中返回 return { setUserName:setName, getUserName:getName } } let obj =fun() //将fun函数返回值(对象)赋给obj console.log('用户名:',obj.getUserName()) //蜗牛学苑 obj.setUserName('石油学苑') console.log('用户名:',obj.getUserName()) //石油学苑
(7) realizes iteration through closure
let arr = ['aa','bb','cc'] function fn(temp){ //外部函数的返回值是闭包 let i = 0 //定义闭包:迭代获取数组元素并返回 return function(){ return temp[i++] || '数组已经遍历结束' } } let f1 = fn(arr) console.log(f1()) //aa console.log(f1()) //bb console.log(f1()) //cc console.log(f1()) //数组已经遍历结束
(8), first distinction (with the same parameters, the function will not Repeat)
var fn = (function(){ var arr = [] //用来缓存的数组 return function(val){ if(arr.indexOf(val) == -1){ //缓存中没有则表示需要执行 arr.push(val) //将参数push到缓存数组中 console.log('函数被执行了',arr); //这里写想要执行的函数 } else { console.log('此次函数不需要执行'); } console.log('函数调用完打印一下,方便查看缓存的数组:',arr); } })() fn(10) fn(10) fn(1000) fn(20) fn(1000)
Note
(1) Find out who the closure function is
(2) Identify the closure clearly Return value, return value of external function
4. Summary of closure
What is closure: closure Is a function (one scope can access the local variables of another function).
What is the function of closure: extending the scope of the variable.
No closure is generated because there are no local variables, so the global variables are accessed
The Window
let name = 'The Window' let object = { name: 'My Object', getNameFunc(){ return function(){ return this.name } } } let f = object.getNameFunc() console.log(f()) //The Window
A closure is generated: because this is assigned to that inside the function, pointing to the object object.
let name = 'The Window' let object = { name: 'My Object', getNameFunc(){ let that = this return function(){ return that.name } } } let f = object.getNameFunc() console.log(f()) //My Object
Notes on using closures
1) Since closures cause all variables in the function to be stored in memory, memory consumption is very large , so closures cannot be abused, otherwise it will cause performance problems on the web page, and may cause memory leaks in IE. The solution is to delete all unused local variables before exiting the function.
2) The closure will change the value of the variable inside the parent function outside the parent function. Therefore, if you use the parent function as an object, the closure as its public method, and the internal variables as its private value, you must be careful not to Feel free to change the value of the variable inside the parent function.
[Recommended learning: javascript video tutorial]
The above is the detailed content of Does es6 have closures?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In C++, a closure is a lambda expression that can access external variables. To create a closure, capture the outer variable in the lambda expression. Closures provide advantages such as reusability, information hiding, and delayed evaluation. They are useful in real-world situations such as event handlers, where the closure can still access the outer variables even if they are destroyed.

C++ Lambda expressions support closures, which save function scope variables and make them accessible to functions. The syntax is [capture-list](parameters)->return-type{function-body}. capture-list defines the variables to capture. You can use [=] to capture all local variables by value, [&] to capture all local variables by reference, or [variable1, variable2,...] to capture specific variables. Lambda expressions can only access captured variables but cannot modify the original value.

A closure is a nested function that can access variables in the scope of the outer function. Its advantages include data encapsulation, state retention, and flexibility. Disadvantages include memory consumption, performance impact, and debugging complexity. Additionally, closures can create anonymous functions and pass them to other functions as callbacks or arguments.

Title: Memory leaks caused by closures and solutions Introduction: Closures are a very common concept in JavaScript, which allow internal functions to access variables of external functions. However, closures can cause memory leaks if used incorrectly. This article will explore the memory leak problem caused by closures and provide solutions and specific code examples. 1. Memory leaks caused by closures The characteristic of closures is that internal functions can access variables of external functions, which means that variables referenced in closures will not be garbage collected. If used improperly,

The impact of function pointers and closures on Go performance is as follows: Function pointers: Slightly slower than direct calls, but improves readability and reusability. Closures: Typically slower, but encapsulate data and behavior. Practical case: Function pointers can optimize sorting algorithms, and closures can create event handlers, but they will bring performance losses.

Yes, code simplicity and readability can be optimized through chained calls and closures: chained calls link function calls into a fluent interface. Closures create reusable blocks of code and access variables outside functions.

Closures in Java allow inner functions to access outer scope variables even if the outer function has exited. Implemented through anonymous inner classes, the inner class holds a reference to the outer class and keeps the outer variables active. Closures increase code flexibility, but you need to be aware of the risk of memory leaks because references to external variables by anonymous inner classes keep those variables alive.

Go language function closures play a vital role in unit testing: Capturing values: Closures can access variables in the outer scope, allowing test parameters to be captured and reused in nested functions. Simplify test code: By capturing values, closures simplify test code by eliminating the need to repeatedly set parameters for each loop. Improve readability: Use closures to organize test logic, making test code clearer and easier to read.
