Perception: 🌟🌟🌟🌟🌟

Taste: Iced watermelon

Cooking time: 20min




The first rule of flirting is that girls love fairy tales.

Let’s start with a fairy tale

// There was a princess
// She lives in a wonderful world full of adventures
// She met her prince charming, who took her around the world on a unicorn
// Fought dragons, encountered talking squirrels, and many other fantasizing things.
function princess () {
    var adventrures = [];
    function princeCharming () {};
    var unicorn = {};
    var dragons = [];
    var squirrel = "Hello!";
    // But she had to return to her monotonous world of housework and adults.
    return {
    // She often tells the people around her about her wonderful experiences as a princess.
      story:function () {
          return adventures[adventures.length - 1]; }}}// But all they saw was a little girl telling stories about magic and fantasy
var littleGril = princess();
littleGril.story();
// Even if the grown-ups knew that she was a real princess, they would not believe the so-called unicorn or dragon, because they would never see them
// Adults say they only exist in the little girl's imagination
// But we know the real truth
// The little girl in it is really a princess
Copy the code

This story comes from an answer from StackOverflow. It doesn’t matter if you don’t understand it. After reading this article, you will come back to see the story, and you will find that you have fully understood my charm The power of closures in JavaScript.

What is a closure?

Closures occur when a function can remember and access the lexical scope in which it is located, even if the function is executed outside the current lexical scope. -- JavaScript you don't know (Vol. 1)

To a 🌰

function demo() {
    var a = 1;
    return function () {
        returna; }}var a = demo();
console.log(a());  / / 1
Copy the code

The composition of closures

A closure consists of two parts: the function, and the environment in which the function is created.

The environment consists of any local variables that were in scope when the closure was created.

The nature of closures

Closures are actuallyJavaScriptSide effects of function scope.

Closures are a special kind of object.

This is not because JavaScript uses closures intentionally, but because JavaScript functions can use variables that are outside of functions, and this code fits the definition of a closure just fine.

In JavaScript, the variable object of an external function is supposed to be destroyed after it is called, but the closure prevents that from being destroyed. We can still access the variable object of the external function.

Further, normally, the scope of a function and all its variables are destroyed at the end of the function’s execution. However, if a closure is created, the scope of the function is kept until the closure no longer exists.

function addCalculator (x) {
    return function (y) {
        returnx + y; }}var add1 = addCalculator(1);

console.log(add1(1)); / / 2

// Release references to closures
add1 = null;

console.log(add1(1)); //Uncaught TypeError: add1 is not a function

Copy the code

Application of closures

What can we do with closures?

Those of you who know Java may know that Java supports private methods, which can only be called by other methods in a class, but JavaScript does not provide native support for this, so we can simulate private methods through closures.

Private methods naturally have the benefits of private methods, which help limit access to the code and reduce global pollution by preventing non-core methods from interfering with the code’s public interface.

To a 🌰

var calculator = (function(){
    var a = 1;
    function addCalculator(val){
        a += val
    }
    return {
        add1:function() {
            addCalculator(1);
        },
        add2:function() {
            addCalculator(2);
        },
        result:function() {
            return a
        }
    }
})();

console.log(calculator.result());  / / 1
calculator.add1();
console.log(calculator.result());  / / 2
calculator.add2();
console.log(calculator.result());  / / 4
Copy the code

This is also called a Module pattern.

Considerations for using closures

A memory leak

Because closures can cause variables in a function to be stored in memory, which is a big memory drain, we don’t want to abuse closures if they aren’t needed for specific tasks.

This has been mentioned in many blogs, but it’s not entirely true.

Knock on the blackboard!!

Improperly used closures can cause memory leaks before IE(IE9). Because the garbage collection algorithm used by its JavaScript engine is reference counting, circular references will cause GC(described below) to fail to collect garbage.

For details on closure testing for each browser, see Sitto – JS Closure Testing

Garbage collection mechanism

All 9102 years, the whole country began to implement garbage classification, you actually do not know the garbage recycling mechanism, hurry to learn!

Garbage Collection is also known as Garbage Collection.

GC treats unused memory space as garbage, finds it and reclaims it so that the programmer can use it again.

Not all languages have GC, but high level languages such as Java, JavaScript, and Python. In a world without GC, the programmer would have to manage memory manually. For example, in C we can manage memory by malloc/free, and in C++ we can manage memory by new/delete.

Garbage collection algorithm

Because this section is a lot of content, this article will only briefly explain, if you want to learn more about the garbage collection algorithm students can get learning materials at the end of the article.

GC mark-clear algorithm

The first memorable GC algorithm in the world was the GC mark-clear algorithm. Because half a century later, it’s still a great algorithm for all kinds of processors.

GC mark-clear algorithm consists of the marking stage and the clearing stage. In the marking stage, all the active objects are marked correspondingly, and in the clearing stage, those unmarked objects, that is, inactive objects, are recycled. Depth first search is used when searching for objects and marking them, searching tree structures as deep as possible.

Advantages:

1. Simple algorithm and easy implementation.

2. Compatible with the conservative GC algorithm.

Disadvantages:

1. Fragmentation occurs during use, as with the Windows file system, resulting in numerous small chunks scattered all over the heap.

2. Allocation speed. Due to the discontinuity of blocks, the algorithm needs to traverse the idle linked list to find a large enough block every time it allocates.

Reference counting

This approach introduces the concept of counters to represent the “popularity” of an object, that is, how many programs have referenced the object. When the counter (number of references) is zero, garbage is collected immediately.

Advantages:

1. Garbage can be collected immediately.

2. The maximum pause time is short.

3. And there is no need to look along the pointer.

Disadvantages:

1. The circular reference mentioned above cannot be recycled.

2. And it’s complicated to implement.

3. The increase or decrease of the counter value is very heavy.

4. At the same time, the counter needs to occupy a large number of bits, resulting in the use of memory space is greatly reduced.

Software engineering has no silver bullet, these shortcomings also have the corresponding way to solve, if you want to in-depth understanding of garbage recycling algorithm, can buy garbage recycling algorithm and implementation of this book to see, it is recommended to support legitimate.

Welcome to follow my personal official account, the article will be sent synchronously, the background reply [welfare] can get massive learning materials for free.

Your front dining hall, remember to eat on time.

Ps: You can also reply to the background garbage recycling can get a related information ~