search
HomeWeb Front-endFront-end Q&ADoes es6 have closures?

Does es6 have closures?

Nov 21, 2022 pm 06:57 PM
javascriptes6Closure

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

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 <p><strong>(6) Encapsulate closures in In the object, </strong></p><pre class="brush:php;toolbar:false">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 accessedThe Window

let name = &#39;The Window&#39;
    let object = {
        name: &#39;My Object&#39;,
        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!

Statement
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
HTML and React's Integration: A Practical GuideHTML and React's Integration: A Practical GuideApr 21, 2025 am 12:16 AM

HTML and React can be seamlessly integrated through JSX to build an efficient user interface. 1) Embed HTML elements using JSX, 2) Optimize rendering performance using virtual DOM, 3) Manage and render HTML structures through componentization. This integration method is not only intuitive, but also improves application performance.

React and HTML: Rendering Data and Handling EventsReact and HTML: Rendering Data and Handling EventsApr 20, 2025 am 12:21 AM

React efficiently renders data through state and props, and handles user events through the synthesis event system. 1) Use useState to manage state, such as the counter example. 2) Event processing is implemented by adding functions in JSX, such as button clicks. 3) The key attribute is required to render the list, such as the TodoList component. 4) For form processing, useState and e.preventDefault(), such as Form components.

The Backend Connection: How React Interacts with ServersThe Backend Connection: How React Interacts with ServersApr 20, 2025 am 12:19 AM

React interacts with the server through HTTP requests to obtain, send, update and delete data. 1) User operation triggers events, 2) Initiate HTTP requests, 3) Process server responses, 4) Update component status and re-render.

React: Focusing on the User Interface (Frontend)React: Focusing on the User Interface (Frontend)Apr 20, 2025 am 12:18 AM

React is a JavaScript library for building user interfaces that improves efficiency through component development and virtual DOM. 1. Components and JSX: Use JSX syntax to define components to enhance code intuitiveness and quality. 2. Virtual DOM and Rendering: Optimize rendering performance through virtual DOM and diff algorithms. 3. State management and Hooks: Hooks such as useState and useEffect simplify state management and side effects handling. 4. Example of usage: From basic forms to advanced global state management, use the ContextAPI. 5. Common errors and debugging: Avoid improper state management and component update problems, and use ReactDevTools to debug. 6. Performance optimization and optimality

React's Role: Frontend or Backend? Clarifying the DistinctionReact's Role: Frontend or Backend? Clarifying the DistinctionApr 20, 2025 am 12:15 AM

Reactisafrontendlibrary,focusedonbuildinguserinterfaces.ItmanagesUIstateandupdatesefficientlyusingavirtualDOM,andinteractswithbackendservicesviaAPIsfordatahandling,butdoesnotprocessorstoredataitself.

React in the HTML: Building Interactive User InterfacesReact in the HTML: Building Interactive User InterfacesApr 20, 2025 am 12:05 AM

React can be embedded in HTML to enhance or completely rewrite traditional HTML pages. 1) The basic steps to using React include adding a root div in HTML and rendering the React component via ReactDOM.render(). 2) More advanced applications include using useState to manage state and implement complex UI interactions such as counters and to-do lists. 3) Optimization and best practices include code segmentation, lazy loading and using React.memo and useMemo to improve performance. Through these methods, developers can leverage the power of React to build dynamic and responsive user interfaces.

React: The Foundation for Modern Frontend DevelopmentReact: The Foundation for Modern Frontend DevelopmentApr 19, 2025 am 12:23 AM

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

The Future of React: Trends and Innovations in Web DevelopmentThe Future of React: Trends and Innovations in Web DevelopmentApr 19, 2025 am 12:22 AM

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.