JavascriptScope
Scope-a collection of accessible variables.
a global variable or function can overwrite a variable or function of a window object;
Local Variables and Window objects can override global variables and functions.
JavaScript Scopes
In JavaScript, objects and functions are also variables.
In JavaScript, scopes are a collection of accessible variables, objects, and functions.
JavaScript function Scope: scope is modified within a function.
Note: because local variables are only used within functions, different functions can use variables of the same name.
Local variables are created when the function starts executing, and local variables are automatically destroyed when the function finishes executing.
JavaScript Global Variables
A variable is defined outside a function, which is a global variable.
Global variables have global scope : All scripts and functions in a Web page can be used.
Note: If a variable is not declared within a function (without using the var keyword), the variable is a global variable.
The following instance is carname within a function, but is a global variable.
1<! DOCTYPE html>234<meta charset= "Utf-8" >5<title> Rookie Tutorial (runoob.com) </title>67<body>8 9<p> Global variables can be accessed within any script and function. </p>Ten<p id= "Demo" ></p> One<script> A varCarname = "Volvo"; - myFunction (); - functionmyFunction () the { -document.getElementById ("Demo"). InnerHTML = -"I can show" +Carname; - } +</script> - +</body> A
JavaScript Variable life cycleThe JavaScript variable life cycle is initialized when it declares.
Local variables are destroyed after the function has finished executing.
Global variables are destroyed after the page is closed.
function parametersfunction parameters only work within a function, which is a local variable.
Global variables in HTMLIn HTML, a global variable is a Window object: All data variables belong to the window object .
1<! DOCTYPE html>234<meta charset= "Utf-8" >5<title> Rookie Tutorial (runoob.com) </title>67<body>8 9<p>Ten in HTML, all global variables will become window variables. One</p> A<p id= "Demo" ></p> -<script> - myFunction (); thedocument.getElementById ("Demo"). InnerHTML = -"I can show" +Window.carname; - functionmyFunction () - { +Carname = "Volvo"; - } +</script> A at</body> -Self-study JavaScript (i) variable-scope