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

How to apply closure in JavaScript

2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

Today, the editor will share with you the relevant knowledge points about how to apply closures in JavaScript. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look.

What is closure (Closure)

Simply put, a closure is a function that has access to variables in the scope of another function.

MDN says that a closure is a special object. It consists of two parts: the function and the environment in which the function is created. The environment consists of any local variables in the scope when the closure is created.

However, I found a lot of information on the Internet, and they have different definitions of closures, so I don't know how to define closures, so I don't want to define them at all.

Tao can be Tao, very Tao; name can be name, very name.

Generate a closure

The most common way to create closures is to create one function inside another. The closure in the following example is a closure:

Function func () {var a = 1J b = 2; function closure () {return aqb;} return closure;}

The scope chain of a closure contains its own scope, as well as the scope and global scope of the function that contains it.

Considerations for closures

Typically, the scope of a function and all its variables are destroyed at the end of the function execution. However, after you create a closure, the scope of the function is saved until the closure does not exist.

Function makeAdder (x) {return function (y) {return x + y;} var add5 = makeAdder (5); var add10 = makeAdder (10); console.log (add5 (2)); / / 7 console.log (add10 (2)); / / 12 / / release the reference to the closure add5 = null; add10 = null

Both add5 and add10 are closures. They share the same function definition, but save different environments. In an add5 environment, x is 5. In add10, x is 10. * references to closures by add5 and add10 are released through null.

In javascript, if an object is no longer referenced, the object will be reclaimed by the garbage collection mechanism

If two objects refer to each other and are no longer referenced by the third party, the two objects that reference each other will also be recycled.

A closure can only get a value that contains any variable in a function, because the closure holds the entire variable object, not a particular variable.

Function test () {var arr = []; for (var I = 0 console.log I < 10 console.log I +) {arr [I] = function () {return I;};} for (var a = 0 console.log a < 10 X a +) {console.log (arr [a] ());}} test (); / / print 10 consecutive 10

For the above case, if we change the code as follows:

Function test () {var arr = []; for (let I = 0 console.log I < 10 var I +) {/ / only changes have been made here arr [I] = function () {console.log I;};} for (arr [a] ()) {console.log (arr [a] ());}} test (); / / print 0 to 9

For an explanation of the above two codes, please see my question on segmentfault: link

This objects in closures

Var name = "The Window"; var obj = {name: "My Object", getName: function () {return function () {return this.name;};}}; console.log (obj.getName () ()); / / The Window

Obj.getName () () actually calls an anonymous function in the global scope, and this points to window. Here, it is important to understand that the function name is separated from the function function (or function value). Don't think that the internal this of the function points to wherever the function is. The execution environment of anonymous functions is global, so their this objects usually point to window.

Var name = "The Window"; var obj = {name: "My Object", getName: function () {var that = this; return function () {return that.name;};}}; console.log (obj.getName () ()); / / My Object

Application of closure

The main place to apply closures is to design proprietary methods and variables.

Any variable defined in a function can be considered private because it cannot be accessed outside the function. Private variables include parameters of the function, local variables, and other functions defined within the function.

Public methods that have access to private variables are called privileged methods (privileged method).

Function Animal () {/ / private variable var series = "mammal"; function run () {console.log ("runners!");} / / privileged method this.getSeries = function () {return series;};}

Module mode (The Module Pattern): create private variables and methods for singletons.

Singleton (singleton): an object with only one instance. JavaScript generally creates a singleton object literally.

Var singleton = {name: "percy", speak:function () {console.log ("arranging everything!");}, getName: function () {return this.name;}}

The above is the singleton created by the normal mode. Here is the singleton created using the module mode:

Var singleton = (function () {/ / private variable var age = 22; var speak = function () {console.log ("proprietorship!");}; / / privileged (or public) properties and methods return {name: "percy", getAge: function () {return age;}};})

The purpose of the anonymous function * * is to create closures and to build namespaces to reduce the use of global variables. Thus, the closure modular code is used to reduce the pollution of global variables.

Var objEvent = objEvent | | {}; (function () {var addEvent = function () {/ / some code}; function removeEvent () {/ / some code} objEvent.addEvent = addEvent; objEvent.removeEvent = removeEvent;}) ()

In this code, the functions addEvent and removeEvent are local variables, but we can use it through the global variable objEvent, which greatly reduces the use of global variables and enhances the security of the web page.

A closure counter

Var countNumber = (function () {var num = 0; return function () {return + + num;};}) ()

Defects of closures

The disadvantage of closures is that resident memory increases memory usage, and improper use can easily lead to memory leaks.

If closures are not needed for some special task, it is unwise to create functions in other functions when not necessary, because closures have a negative impact on script performance, including processing speed and memory consumption.

* and some more interview questions about closures

In the following code, the tag? What are the local outputs of?

Function fun (n var o) {console.log (o); return {fun: function (m) {return fun (m);}};} var a = fun (0); / /? A.fun (1); / /? A.fun (2); / /? A.fun (3) / /? Var b = fun (0) .fun (1) .fun (2) .fun (3); / /? Var c = fun (0) .fun (1) / /? C.fun (2); / /? C.fun (3); / /? undefined 2000 undefined, 0,1,2 undefined, 011 and above are all the contents of the article "how to apply closures in JavaScript". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

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: 210

*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

Internet Technology

Wechat

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

12
Report