Does es6 have closures?

青灯夜游
Release: 2022-11-21 18:57:17
Original
1317 people have browsed it

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.

Does es6 have closures?

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
Copy after login

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
Copy after login
// fn 外面的作用域可以访问fn 内部的局部变量 function fn(){ let num = 10 // 方法二: 直接返回函数 return function(){ console.log(num) } } let f = fn() f() //10
Copy after login

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
Copy after login

(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()); //曹操
Copy after login

(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)
Copy after login

(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 }
Copy after login

(5) Loop assignment

(function(){ for (let i = 1; i <= 10; i++) { ( function(j){ setTimeout(function(){ console.log(j); },j*1000) } )(i) } })()
Copy after login

(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()) //石油学苑
Copy after login

(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()) //数组已经遍历结束
Copy after login

(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)
Copy after login

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 accessedThe 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
Copy after login

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
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!