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

Shared JavaScript closure

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article focuses on "sharing JavaScript closures". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "sharing JavaScript closures".

1. Overview

Closure (closures), which is interpreted in MDN as:

Closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope). In other words, these functions' remember' the environment in which they were created.

Closures are functions that can access independent (free) variables (variables are used locally but defined in a closed scope). In other words, these functions can "remember" the environment in which it was created.

Closure is a feature of JavaScript language, of course, it is also a major difficulty, many high-level applications rely on closures, or we usually use closures inadvertently in the coding process.

two。 Domain chain

In understanding closures, the first step is to understand the scope chain in JavaScript.

There are two scopes in JavaScript: global scope and function scope (block-level scope was introduced in ES6).

The variables defined in the function can only be used in the body of this function, and the variables defined inside the body of the function cannot be called directly outside the function, but the variables defined in the global scope can be called in the function.

If there is a definition of an embedded function in the function, the variables defined in the external function or the variables in the global scope can be accessed in the embedded function, but the variables defined in the embedded function cannot be accessed in the external function. In this way, a scope chain is formed, that is, embedded functions can call variables defined in parent or ancestor functions, but parent functions cannot call variables defined in child or descendant functions.

Function outer () {

Var outVar = 10

Function inner () {

Var inVar = 20

Console.log ("call external function variable outVar =" + outVar in inner)

}

Inner ()

Console.log ("call the embedded function variable inVar =" + inVar in outer)

}

Outer ()

Execution result:

Call the external function variable outVar = 10 in inner

ReferenceError: Can't find variable: inVar

In JavaScript, the scope of a variable is determined by its position in the source code, and nested functions can access variables declared in their outer scope.

3. Closure

If there is such a requirement, we need to use variables within the function externally, but normally, it is not accessible through direct calls, which requires a workaround.

Function outer () {

Var I = 1

Var inner = function () {

Return + + I

}

Return inner

}

Var result = outer ()

Console.log ("first call:" + result ())

Console.log ("second call:" + result ())

Console.log ("third call:" + result ())

Execution result:

First call: 2

Second call: 3

Third call: 4

In the above example, we use the variable I inside the outer function, which is incremented by 1 on the basis of the original value for each print. Because it cannot be accessed directly through the variable name outside the function, and the internal inner function can access the external function variable I, it returns the reference inner of the internal function, so that when the call to the outer function ends, the reference placed in the result is actually the reference to the embedded function, so you can continue to use the variable I defined inside the outer function. This is the closure.

I believe you have written similar code snippets for timers commonly used in the past:

Function fn () {

Var I = 0

Var timer = setInterval (function () {

Console.log (iTunes +)

If (I > 10)

ClearInterval (timer)

}, 50)

}

Fn ()

After the call to the fn function, the scope of the local variables I and timer inside the fn function should end, but the values of these two variables can still be used during the asynchronous execution of the setInterval () function. This is also a typical use of closures.

4. A story

Before illustrating what scenarios closures can apply, I like the following example.

A long time ago:

There is a princess.

Function princess () {

She lived in a wonderful world full of adventure and met her Prince Charming. Prince Charming took her around the world on a unicorn, fighting dragons, bumping into talking animals, and many other incredible novelties.

Var adventures = []

Function princeCharming () {/ *... /}

Var unicorn = {/ *... * /}

Dragons = [/ *... * /]

Squirrel = "Hello!"

But she had to go back to her boring kingdom and routinely meet the adults.

Return {

She will often share with adults her recent fantastic adventures as a princess.

SayStory: function () {

Return adventures [adventures.length-1]

}

}

}

But in the eyes of adults, the princess is just a little girl.

Var littleGirl = princess ()

. Telling some magical and fantasy stories.

LittleGirl.sayStory ()

Even though all the adults knew that the little girl in front of them was a real princess, they never believed in dragons or unicorns because they had never seen them before. Adults say they only exist in the imagination of little girls.

But we know that the little girl is telling the truth.

5. Closure applicable scenario

Generally speaking, closures can be used in the following two scenarios:

Maintain variables, such as cached data, in memory

Protect variables in a function, such as setting private properties for an object

5.1 caching data

A more common example is the use of loops to bind events to elements.

When each div element is clicked, the index of the currently clicked div pops up correctly:

Div-1

Div-2

Div-3

Div-4

Div-5

If you use the following words:

At this point, when you click on each div, the pop-up result is that the div index you click is: 5. This is because event handling is asynchronous, but event binding is synchronous, performing five operations on the loop body first, binding onclick events for each div.

In this process, the value of the variable I keeps increasing and changing, and when all div elements are traversed, the value of I increases to 5 and exits the loop structure. After the function handle call is finished, because there is still a reference to the variable I in the event response program, if the resource of the variable I is released, it will cause the event response program to execute an error, so in order to ensure that the variable I can still be used correctly in the event response program, the value of the variable I will always be kept in memory, but the value of the retained I will be 5.

If you want to output the index value correctly, you can use the closure to modify the following:

When binding events for each div, calling the clk () function passes the variable value I associated with div to the clk () function for internal use, because a reference to the embedded function is returned internally, and the implementation of this embedded function depends on the local variable index in the external function, so the value of the index variable is cached in memory.

Because each div binding event calls the clk () function to implement the event binding operation, the value of the corresponding variable index I is also cached in memory, but this value is not cached by the name of I. When we test it again, we can print out the index of the div we clicked correctly.

Of course, the above functions can also be implemented through custom attributes:

Or through the let command:

5.2 set private properties for objects

If there is an object with an attribute of age, we want to limit the value of age to between 18 and 25 years old, and implement it in an object-oriented way similar to Java, which can be simulated as follows:

Age represents the age of the student, if such a variable can be modified for anyone, then given a negative value, such as-35, although it is no problem grammatically, but logically speaking, it is impossible for a person to be-35 years old, so in order to ensure the security of this kind of data, we can use closure to solve.

For the local variable age within the Student function, the resource should be released after the Student () function ends through the new call, but there is still a reference to it in the object's getAge/setAge method, and releasing resources will cause the getAge/setAge function to not be completed normally, so its value will be stored in memory. However, when we want to modify the age age value, because of its scope problem, we cannot modify it directly by calling age outside the Student function. We can only use the provided setAge method interface to modify the age value, which ensures the security of the age modification assignment.

6. A little misunderstanding.

In the past, when looking up data, we often saw the saying that closures should not be used easily, otherwise it would easily cause memory leaks.

Until I read this article: "js closure testing"

The variables in the closure are the variables we need to use (lives), and memory leaks usually mean that the variables that cannot be accessed still occupy the memory space and cannot be reused. Obviously, closures do not belong to inaccessible memory space.

The reason for this is probably because of IE, especially IE6's bug. Of course, this is a problem with IE browsers, not closures.

Modern browsers are mostly optimized for garbage collection in the case of closures in JavaScript engines, so we don't have to worry about memory leaks.

At this point, I believe you have a deeper understanding of "sharing JavaScript closures". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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