How to realize the local and global scope of JavaScript
This article mainly introduces the relevant knowledge of "how to realize the local and global scope of JavaScript". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to realize the local and global scope of JavaScript" can help you solve the problem.
Scope refers to the collection of variables that you have access to.
JavaScript function scope
There are two scope types in JavaScript:
Global scope
JavaScript has a function scope: each function creates a new scope.
The scope determines the accessibility (visibility) of these variables.
Variables defined within a function are inaccessible (invisible) from outside the function.
Local JavaScript variable
Variables declared in the JavaScript function become local variables of the function.
The scope of local variables is local: they can only be accessed within the function.
Example
/ / the code here cannot use the carName variable
Function myFunction () {
Var carName = "porsche"
/ / the code here can use the carName variable
}
Because you can only recognize local variables within a function, you can use variables of the same name in different functions.
Local variables are created at the beginning of the function and deleted when the function is completed.
Global JavaScript variable
Variables declared outside the function become global variables.
The scope of a global variable is global: it can be accessed by all scripts and functions of a web page.
Example
Var carName = "porsche"
/ / the code here can use the carName variable
Function myFunction () {
/ / the code here can also use the carName variable
}
This is the end of the introduction to "how to achieve the local and global scope of JavaScript". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.