Home Web Front-end JS Tutorial Analysis of the occasions and advantages and disadvantages of js closure_javascript skills

Analysis of the occasions and advantages and disadvantages of js closure_javascript skills

May 16, 2016 pm 03:53 PM
js Advantages and Disadvantages Closure

First the code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

//函数a

function a()

{

var i=0;

//函数b

function b()

{

alert(++i);

}

return b;

}

//函数c

var c = a();

c();

Copy after login

Code features:

1. Function b is nested inside function a;
2. Function a returns function b.
When the internal function b of function a in the code is referenced by a variable c outside function a, this is called creating a closure. Sometimes function b can also be returned by an anonymous function, that is, return function(){};

Advantages: 1. Protect the security of variables within the function and enhance encapsulation. 2. Maintain a variable in the memory (using too much will become a disadvantage and occupy memory)
The reason why closures occupy resources is that when function a ends, variable i will not be destroyed because function a ends, because the execution of b depends on the variables in a.
Not suitable for the scenario: the function that returns the closure is a very large function

The typical framework for closure should be jquery.

Closures are a major feature of the JavaScript language. The main uses of closures are to design private methods and variables.
This is more obvious when making a framework. Some methods and attributes are only used in the operation logic process. You don’t want to allow external modification of these attributes, so you can design a closure to only provide method access.

The disadvantage of closures is that they are resident in memory, which will increase memory usage. Improper use can easily cause memory leaks.

To summarize:

Advantages:

1. Logical continuity. When the closure is used as a parameter of another function call, it prevents you from breaking away from the current logic and writing additional logic separately.
2. Facilitate calling local variables of the context.
3. Strengthen encapsulation. An extension of point 2 can protect variables.

Disadvantages:

Closures have a very serious problem, which is the problem of memory waste. This memory waste is not only because it is resident in memory, but more importantly, improper use of closures will cause the generation of invalid memory. See below Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

var array = [];

function abc() {

var foo = function(){

}

array.push(foo);

return foo;

}

for(var i = 0 ; i < 10000; i ++)

{

abc();

}

 

alert(array[0] == array[1]);

Copy after login

Through the above test, we will see that the addresses of the same logical closure generated by the execution of abc() ten thousand times are not the same, which means that it produces a bunch of identical Function objects, so there are The advantage is that you can use factory mode to generate functions for use. However, if you accidentally use closures as normal logic, memory garbage will inevitably be caused. It may be easier to understand if you change the syntax:

1

var foo = new Function();

Copy after login

So regarding closures, as far as my own habits are concerned, I don’t use them if I can. If they must be used, then find a way to keep the number of closure objects small or even unique.

The above is the entire content of this article, I hope you all like it.

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Must read before purchasing a system: Analysis of the advantages and disadvantages of Win11 and Win10 Must read before purchasing a system: Analysis of the advantages and disadvantages of Win11 and Win10 Mar 28, 2024 pm 01:33 PM

In today's information age, personal computers play an important role as an indispensable tool in our daily lives. As one of the core software of computers, the operating system affects our usage experience and work efficiency. In the market, Microsoft's Windows operating system has always occupied a dominant position, and now people face the choice between the latest Windows 11 and the old Windows 10. For ordinary consumers, when choosing an operating system, they do not just look at the version number, but also understand its advantages and disadvantages.

What is the meaning of closure in C++ lambda expression? What is the meaning of closure in C++ lambda expression? Apr 17, 2024 pm 06:15 PM

In C++, a closure is a lambda expression that can access external variables. To create a closure, capture the outer variable in the lambda expression. Closures provide advantages such as reusability, information hiding, and delayed evaluation. They are useful in real-world situations such as event handlers, where the closure can still access the outer variables even if they are destroyed.

What are the advantages and disadvantages of templating? What are the advantages and disadvantages of templating? May 08, 2024 pm 03:51 PM

Templating: Pros and Cons Templating is a powerful programming technique that allows you to create reusable blocks of code. It offers a range of advantages, but also some disadvantages. Pros: Code Reusability: Templating allows you to create common code that can be reused throughout your application, reducing duplication and maintenance efforts. Consistency: Templating ensures that code snippets are implemented the same way in different locations, improving code consistency and readability. Maintainability: Changes to a template are reflected simultaneously in all code that uses it, simplifying maintenance and updates. Efficiency: Templating saves time and effort because you don't have to write the same code over and over again. Flexibility: Templating allows you to create configurable blocks of code that can be easily adapted to different application needs. shortcoming

What are the advantages and disadvantages of how Java Servlets work? What are the advantages and disadvantages of how Java Servlets work? Apr 16, 2024 pm 03:18 PM

JavaServlet is a Java class used to build dynamic web pages and serves as a bridge between client and server. Working principle: receive requests, initialize Servlet, process requests, generate responses and close Servlet. Pros: Portable, scalable, secure and easy to use. Disadvantages: Overhead, coupling, and state management. Practical case: Create a simple Servlet to display the "Hello, Servlet!" message.

How to implement closure in C++ Lambda expression? How to implement closure in C++ Lambda expression? Jun 01, 2024 pm 05:50 PM

C++ Lambda expressions support closures, which save function scope variables and make them accessible to functions. The syntax is [capture-list](parameters)->return-type{function-body}. capture-list defines the variables to capture. You can use [=] to capture all local variables by value, [&] to capture all local variables by reference, or [variable1, variable2,...] to capture specific variables. Lambda expressions can only access captured variables but cannot modify the original value.

What are the advantages and disadvantages of closures in C++ functions? What are the advantages and disadvantages of closures in C++ functions? Apr 25, 2024 pm 01:33 PM

A closure is a nested function that can access variables in the scope of the outer function. Its advantages include data encapsulation, state retention, and flexibility. Disadvantages include memory consumption, performance impact, and debugging complexity. Additionally, closures can create anonymous functions and pass them to other functions as callbacks or arguments.

Comparison of the advantages and disadvantages of PHP frameworks: Which one is better? Comparison of the advantages and disadvantages of PHP frameworks: Which one is better? Jun 04, 2024 pm 03:36 PM

The choice of PHP framework depends on project needs and developer skills: Laravel: rich in features and active community, but has a steep learning curve and high performance overhead. CodeIgniter: lightweight and easy to extend, but has limited functionality and less documentation. Symfony: Modular, strong community, but complex, performance issues. ZendFramework: enterprise-grade, stable and reliable, but bulky and expensive to license. Slim: micro-framework, fast, but with limited functionality and a steep learning curve.

See all articles