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 does closure mean in js

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

Share

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

This article analyzes "what does closure mean in js"? The content is detailed and easy to understand. Friends who are interested in "what is the meaning of closure in js" can follow the editor's train of thought to read it slowly and deeply. I hope it will be helpful to you after reading. Let's learn more about what closures mean in js with the editor.

What is closure?

What closures are and why there are closures everywhere in js.

A closure is a function that has access to variables in the scope of another function, and this function, together with the referenced variable, forms the closure

The text description is difficult to understand. You can see it at a glance by looking at the code.

Function test () {var a = 1 var b = function () {console.log (a)} return b}

In the above code example, variable an is in the scope of the function test, but variable a can be accessed in function b.

Apply the concept of closure, that is, function b has the right to access the variable an in the scope of function test, and then function b and variable a form a closure.

After reading the above example, do you suddenly realize that this is what we often write in the code? So js is full of closures.

How to observe closures

If we don't know much about closures at first, how do we know that a closure has been written in the code? A trick to teach you to find the closure.

Function test () {let a = 1 return function test1 () {debugger console.log (a)}} test () ()

As in the above code, when we execute the debugger keyword, we can open the developer modulation tool of the browser. At this time, we can see the word Closure in the call stack, which means that we have written a closure.

The misunderstanding of closure

After talking about the concept of closure, let's talk about some misunderstandings that people may have about closure.

1. The generation of closures needs to be exposed using return

First of all, from the concept of closure, it does not mention that the closure needs to be exposed to the function before it is called a closure, but as long as it references a variable that does not belong to the scope of the current function, it has already generated a closure.

Why there is such a misunderstanding is that we use closures to reference variables in external scope, generally in order to expose this variable or function, so that we can access this variable or function externally, that is to say, exposing closures to the outside of the function is only our business requirement, not a necessary condition for closures.

two。 Closures can cause memory leaks

First of all, we need to know why closures lead to memory leaks, because when we expose closures to the outside of the function, variables in its external scope are still referenced inside the close. as a result, variables in the external scope can not be collected by the garbage collection mechanism, and it is easy to cause memory leaks if the closure is referenced in a loop. But this is caused by the use of closures, not by the nature of the closures themselves, so it is not rigorous to say that closures must lead to memory leaks.

(in addition, the browser's garbage collection mechanism has been optimized after IE9, so it is no longer easy to cause memory leaks.)

Problems caused by closures

As one of the eight traps in js, loop traps are caused by closures.

For (var I = 0; I

< 4; i++) { setTimeout(() =>

{console.log (I)}, 1000)} / / 4,4,4,4

If you execute the above code, you will find that four 4s are printed after 1s, why not print 0,1,2,3, or because the callback function in setTimeout is a closure that refers to the I variable in the external scope, but there is only one I, so a new I is not generated in each callback, so the I variable in the same scope is accessed when printing after 1s, so the printed result is four 4s.

There are two ways to solve the above problems:

One is to use es6's let syntax to generate block-level scopes so that the I variables in each block-level scope do not point to the same I variable and do not affect each other.

For (let I = 0; I

< 4; i++) { setTimeout(() =>

{console.log (I)}, 1000)} / / 0,1,2,3

One is to use an immediate execution function, where the variable I in each immediate execution function is a snapshot of the current external variable I

For (let I = 0; I

< 4; i++) { (function(i) { setTimeout(() =>

{console.log (I)}, 1000)}) (I)} / / 0,1,2,3 closures

After talking so much about the nature of closures, even closures can raise such a big question as loop traps, so what's the use of closures? When asked by the interviewer, you can't say that js is full of closures, so js is full of closure scenarios. So let's talk about some classic usage scenarios of closures.

1. Singleton mode var CreateSingleton = (function () {var instance = null var CreateSingleton = function () {if (instance) return instance return instance = this} return CreateSingleton}) ()

The singleton pattern is a design pattern designed to ensure that there is only one instance object in the global. The above code uses instance to create a closure. Singleton mode ensures that only one pop-up component is particularly useful in the component library.

two。 Corialization of function

Corialization converts a multi-parameter function into several single-parameter function nesting forms, for example: function test (a, b, c) = > function test (a) (b) (c)

Function currying (fn, args) {var _ this = this var len = fn.length var args = args | | [] return function () {var _ args = Array.prototype.slice.call (arguments) Array.prototype.push.apply (args, _ args) if (_ args.length < len) {return currying.call (this, fn, _ args)} return fn.apply (this, _ args)} 3. Use with the immediate execution function to complete the encapsulation of the class library

Closures are often used with immediate execution functions, which can have a powerful effect. As a result, many people are easily misled about the relationship between closures and immediate execution of functions, or even that immediate execution of functions is closures. But this understanding is actually wrong, and there is no relationship between immediate execution of functions and closures.

In the era when jQuery prevailed, all kinds of specifications competed for splendor. Among them, umd specification can be compatible with a variety of environments, mainly in the implementation of its umd header structure.

(function (global, factory) {"use strict"; if (typeof module = "object" & & typeof module.exports = "object") {module.exports = global.document? Factory (global, true): function (w) {if (! w.document) {throw new Error ("jQuery requires a window with a document");} return factory (w);} else {factory (global);}}) (typeof window! = = "undefined"? Window: this, function (window, noGlobal) {})

The above code writing method should be very familiar to those who have used jQuery development.

4. Save private variables

In the actual development process, we sometimes need to cache the calculation results, or save private variables without external access, we can use closures.

In addition, closures are also widely used to implement related functions in the two popular front-end frameworks Vue and React. Specifically, you can flip through the source code.

What kind of language is javascript? javascript is a dynamically typed, weakly typed language, based on object and event-driven, relatively secure, and widely used in client-side web page development. it is also a widely used scripting language for client-side Web development. It is mainly used to add dynamic functions to HTML web pages, and now JavaScript can also be used in web servers, such as Node.js.

So much for sharing what closures mean in js. I hope the above content can improve everyone. If you want to learn more knowledge, please pay more attention to the editor's updates. Thank you for following the website!

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