Case Analysis of JavaScript closure
This article mainly explains the "JavaScript closure case analysis", the article explains the content is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn "JavaScript closure case analysis" bar!
JavaScript variables belong to local or global scope.
Global variables can be locally (private) through closures.
Global variable
The function can access all variables defined within the function, such as:
Case study
Function myFunction () {
Var a = 4
Return a * a
}
But the function can also access variables defined outside the function, such as:
Case study
Var a = 4
Function myFunction () {
Return a * a
}
In this last example, an is a global variable.
In a web page, global variables belong to the window object.
Global variables can be used and modified by all scripts on the page (and in the window).
In the first example, an is a local variable.
Local variables can only be used within the function in which they are defined. It is invisible to other functions and script code.
Global and local variables with the same name are different variables. If you modify one, it will not change the other.
Variables created without the keyword var are always global, even if they are created in a function.
The life cycle of a variable
Global variables live as long as your application (windows, web pages).
Local variables don't live long. They are created when the function is called and are deleted after the function is completed.
Thank you for reading, the above is the content of "case analysis of JavaScript closure". After the study of this article, I believe you have a deeper understanding of the problem of instance analysis of JavaScript closure, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!