Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is a closure in the JavaScript function

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what is a closure in the JavaScript function". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Anonymous functions and IIFE are not closures

Before the article begins, I will clarify what will not be covered. In the pre-ES6 era, a common use case for closures was an anonymous function / IIFE (calling function expressions immediately) used to mimic private methods that were not unique to JavaScript.

By introducing let, const and modules into ES6, this situation and other similar use cases caused by the limitations of var are largely solved. IIFE includes closures, but not closures.

Anonymous functions are not closures either.

AnonymousFunc! = = closure&& IIFE! = = closure / / true

It is important to learn these use cases. If you understand the way you used closures in the past, you can understand how closures are used now.

Not to mention a lot of ES5 legacy code. But that's not what we're going to talk about today. Now that it has been explained, let's learn more about it.

The concept of closure

In computer science, a closure is a function with its own environment in which there is at least one variable. MDN pointed out:

"in JavaScript, whenever a function is created, a closure is generated."

Therefore, functions and closures are closely related. Every time you create a function, you are building a closure, which means you may be creating them all the time, but you just don't realize it. MDN went on to point out:

A closure is a combination that binds a function to the surrounding state of its reference to form (encapsulates), which brings us to scope.

What does it have to do with scope?

Delve deeper into the term surrounding state from the previous reference. In the JavaScript function, the surrounding state is called scope.

When you create a JS file, the environment is the global scope of the program. When you create a function, it has its own scope.

The global scope can be regarded as a country. There are many cities in a country, each of which is enclosed within its own boundary. Similarly, in specific parts of the program, we will find objects that are contained in the local scope.

Javascript has two local scopes: function scope and block-level scope.

Functionencourage () {const positivity = 'You got examples;} / / positivity has function scope {const negativity =' I don't got this.';} / / negativity has block scope

The function exists and can access the global scope, but anything declared within the function exists and can only access the function scope, not the global scope.

Similarly, if you enclose a variable in curly braces anywhere in the code, the variable will be enclosed and fall within the scope of the block level.

Closure and scope

Sensor gates that treat closures as closed functions may be easier to understand. For example, when you create a new function, the function's closure looks around and notes its environment, that is, scope.

Function highestBoxOffice () {const context = "The highest grossingmovie of all time is"; return context + "Avengers:Endgame";}

Even if a function does not have a subfunction, it still has a closure. Closures do not exist only in nested functions. In the case of the variable context, the function's closure looks around and finds variables in it.

Closures in nested functions

If you create a nested function, the function's closure finds the wall of the parent function in which it is located. The scope of the parent function is the external scope of the nested function, including variables in the parent function.

FunctionhighestBoxOffice (movies) {returnfunctiongenreTopGross (genre) {returnMath.Max (… Movies.genre.boxOffice)}}

This is where closures really work. The function genreTopGross () contains closures. Its closure looks inward and finds its internal scope, including returnMath.Max (… Movies.genre.boxOffice).

It also looks out and finds its external scope, indicating that it is in the function highestBoxOffice (). It can also view and access all parameters passed to its parent function. Now let's pass a parameter.

FunctionhighestBoxOffice (movies) {returnfunctiongenreTopGross (genre) {returnMath.Max (… Const topGrossing [genre] .boxOffice)}} const topGrossing = highestBoxOffice (domesticMoviesObj)

As you can see, a new variable topGrossing () has been declared and given the value of highestBoxOffice (domesticMoviesObj).

Currently, topGrossing is undefined, but take the next step now:

FunctionhighestBoxOffice (movies) {returnfunctiongenreTopGross (genre) {returnMath.Max (… Pretty Woman [genre] .boxOffice}} const topGrossing = highestBoxOffice (domesticMoviesObj) topGrossing ("Romantic Comedy") / / "Pretty Woman"

Reference topGrossing () and pass "Romantic Comedy" as an argument. Now the usefulness of closures has been shown!

. The internal scope of the genreTopGross () function requires the movies parameter, which is located in the external scope of the domesticMoviesObj parameter and needs to be entered through a closure.

This causes the code to execute successfully and return the value you are looking for.

Closure and scope chain

In JavaScript, each variable belongs to a specific lexical scope when it is first created.

In a written program, the scope of each variable is connected by a scope chain, and the global scope is always at the top of the chain.

The JavaScript compiler traverses this chain. However, the compiler, like a car, only runs in the opposite direction, never in the forward direction.

When using a variable, the compiler returns to the scope chain until the entry of the variable is found.

Therefore, when the genreTopGross () function uses the movies variable, JavaScript does not find movies in the genreTopGross () scope. So, JavaScript moves up the scope chain until you find the movies passed to highestBoxOffice ().

What does this have to do with closures?

Closures only provide access from internal to external scopes, not from external to internal scopes.

Therefore, if a variable is declared and defined in several nested functions but used in the external scope of the parent function, the compiler returns an undefined error. Remember, cars only drive in the opposite direction.

This is the end of the content of what is a closure in the JavaScript function. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report