JavaScript closures and memory leak issues

Source: Internet
Author: User
Tags closure

Closed Package

One of the most powerful abstractions that you must mention in javascript: closures. What on earth does it do?

1 functionMakeadder (a) {2     return function(b) {3         returnA +b;4     }5 }6 varx = Makeadder (5);7 vary = Makeadder (20);8X (6);// One9Y (7);// -

Makeadder the name itself should be able to explain what the function is for: He created a new adder function with a parameter, which is then loaded on the parameters passed in by the outer layer function when it is called.

What happens here is very similar to the inline function described earlier: a function is defined inside another function, and an intrinsic function can access the variables of the external function. The only difference is that the external function is returned, so common sense tells us that the local variable "should" no longer exist. But they still exist--otherwise adder the function will not work. That is, there are makeAdder two different "replicas" of local variables-one is a equal to 5 and the other is a equal to 20. The result of the operation is that 111 is 27.

Here's what happened. When JavaScript executes a function, a scope object is created to hold the local variables created in the function. He is initialized along with the variable passed in to the function. This is similar to the global object for all of the variables and functions that are saved, but there are still important differences, first, a new, specific scope object is created each time the function is executed ; Unlike global objects (which are accessed as window objects in a browser), you cannot directly access functions and objects from JavaScript code, nor can you iterate through the current functions and properties within the object.

So when called makeAdder , the interpreter creates a scope object with a property: a This property is passed as a parameter to the makeAdder function. makeAddera newly created function is then returned. Typically, the JavaScript garbage collector reclaims the makeAdder created scope object at this point, but the returned function retains a reference to that scope object. The result is that the scope object is not reclaimed by the garbage collector until the makeAdder reference count of the returned function object is zero .

The scope object consists of a chain called a scope chain (scope chain). It is similar to the prototype (prototype) chain, and is used by the JavaScript object system.

A closure is a combination of a function and a scope object in the function being created.

Closures allow you to save state-so they can usually be used in place of objects.

Memory leaks

One disadvantage of using closures is that it can easily lead to memory leaks in Internet Explorer. JavaScript is a garbage-collected language-the object allocates memory when it is created, and when the value of the object's reference count is zero, the browser reclaims the memory. The objects provided by the hosting environment are handled in this way.

The browser host needs to process a large number of objects to depict an HTML page--dom object that is being displayed. The browser is responsible for managing their memory allocations and collections.

IE has its own set of garbage collection mechanisms that can occur when interacting with the garbage collection mechanism provided by JavaScript.

In ie, a memory leak occurs whenever a circular reference is formed between a JavaScript object and a local object . As shown below:

1 function leakmemory () {2     var el = document.getElementById (' el '); 3     var o = {' el ': el}; 4     EL.O = o; 5 }

A circular reference to this code causes memory leaks: IE does not release el o the memory that is and is used until the browser is completely shut down and restarted.

This example often fails to attract attention: memory leaks are generally only noticeable in long-running applications, or when memory leaks occur due to huge amounts of data and loops.

However, in general, there is rarely such a noticeable memory leak-often leaked data structures have multiple layers of references (references), often masking the case of circular references.

closures are prone to unintentional memory leaks. is as follows:

1 function AddHandler () {2     var el = document.getElementById (' el '); 3     function () {4         el.style.backgroundColor = ' red '; 5     }6 }

This code creates an element that turns red when clicked, but it also has a memory leak. Why? Because the el reference to the pair is accidentally placed in an anonymous intrinsic function. This el creates a circular reference between the JavaScript object (the intrinsic function) and the local object () .

There are many ways to solve this problem, the simplest of which is not to use el variables:

1 function AddHandler () {2     function () {3         this. Style.backgroundcolor = ' red '; 4     }; 5 }

Interestingly, one trick to solve the circular reference introduced by closures is to add another closure:

1 functionAddHandler () {2     varClickHandler =function() {3          This. Style.backgroundcolor = ' Red ';4     };5(function() {6         varel = document.getElementById (' el ');7El.onclick =ClickHandler;8     })();9}

The inner function is executed directly and clickHandler hides its contents in the created closure.

Another good way to avoid closures is to break a window.onunload circular reference during an event. Many event libraries can do the job. Note that doing so will make the Bfcache in Firefox not work. So unless there are other necessary reasons, it is best not to register a unload listener in Firefox.

JavaScript closures and memory leak issues

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.