Home > Article > Web Front-end > Sharing the basics of closure based on javascript_Basic knowledge
If you have a good understanding of the basic concepts of scope and functions as independent objects, it will be quite easy to understand the concept of closure and apply it in actual programming practice.
In terms of DOM event processing, most programmers are already using closures without knowing it. In this case, bugs in the JavaScript engine embedded in the browser may cause memory problems. Leaving aside the issue of leakage, even programmers often get confused when debugging themselves.
Use a simple statement to describe the concept of closure in JavaScript: Since in JavaScript, a function is an object, an object is a collection of attributes, and the value of an attribute can be an object, it becomes natural to define a function within a function. If Declare the function inner inside the function func, and then call inner outside the function. This process generates a closure.
Characteristics of closures:
Let’s look at an example first. If you don’t understand the characteristics of JavaScript, it’s difficult to find the reason:
Problems that JavaScript closures should pay attention to:
1. Memory leaks:
In different JavaScript interpreter implementations, due to defects in the interpreter itself, Using closures may cause memory leaks. Memory leaks are a serious problem, which will seriously affect the browser's response speed, reduce user experience, and even cause the browser to become unresponsive. JavaScript interpreters all have a garbage collection mechanism, which generally adopts the form of reference counting. If the reference count of an object is zero, the garbage collection mechanism will recycle it. This process is automatic. However, with the concept of closure, this process becomes complicated. In closure, because local variables may need to be used at some point in the future, the garbage collection mechanism will not handle these external references. If a circular reference occurs, that is, object A refers to B, B refers to C, and C refers to A, this situation will cause the garbage collection mechanism to conclude that its reference count is not zero, thus causing a memory leak. .
2. Contextual reference: