JavaScript Scope
A collection of scope accessible variables.
JavaScript scope
In JavaScript, objects and functions are also variables.
In JavaScript, scope is a collection of accessible variables, objects, and functions.
JavaScript function scope: Scope is modified within the function.
JavaScript local scope
Variables are declared within a function, and the variables are local scope.
Local variables: can only be accessed inside the function.
Instance
// The carName variable cannot be called here
function myFunction() {
var carName = "Volvo";
// The carName variable can be called within the function
}
Try it »
Because Local variables only act within a function, so different functions can use variables with the same name.
Local variables are created when the function starts executing, and they will be automatically destroyed after the function is executed.
JavaScript global variables
Variables defined outside the function are global variables.
Global variables have global scope: all scripts and functions in the web page can be used.
Example
var carName = " Volvo"; // 此处可调用 carName 变量 function myFunction() { // 函数内可调用 carName 变量 }
If a variable is not declared within a function (without using the var keyword), the variable is a global variable.
In the following example, carName is within the function, but is a global variable.
Instance
// 此处可调用 carName 变量 function myFunction() { carName = "Volvo"; // 此处可调用 carName 变量 }
JavaScript variable lifecycle
JavaScript variable lifecycle is initialized when it is declared.
Local variables are destroyed after the function is executed.
Global variables are destroyed after the page is closed.
Function parameters
Function parameters only work within the function and are local variables.
Global variables in HTML
In HTML, global variables are window objects: all data variables belong to the window object.
Instance
//此处可使用 window.carName function myFunction() { carName = "Volvo"; }
Did you know?
Your global variables, or functions, can override the variables or functions of the window object.
Local variables, including window objects, can override global variables and functions.
The above is the content of JavaScript scope in [JavaScript Tutorial]. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!