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: The scope is modified within the function.
JavaScript local scope
Variables are declared within a function and have a local scope.
Local variables: can only be accessed inside the function.
Example
php中文网(php.cn) 局部变量在声明的函数内可以访问。
Run the program and try it
Because local variables only act within the function, it is different Functions can use variables with the same name.
Local variables are created when the function starts executing, and will be automatically destroyed after the function is executed.
JavaScript global variables
A variable defined outside a function is a global variable.
Global variables have global scope: all scripts and functions in the web page can be used.
Example
php中文网(php.cn) 全局变量在任何脚本和函数内均可访问。
Run the program and try it
If the variable is not declared within the function (var is not used keyword), this variable is a global variable.
In the following example, carName is within the function, but is a global variable.
Example
php中文网(php.cn) 如果你的变量没有声明,它将自动成为全局变量:
Run the program and try it
Global variables in HTML
In HTML, global variables are window objects: all data variables belong to the window object.
Example
##Run the program to try itphp中文网(php.cn) 在 HTML 中, 所有全局变量都会成为 window 变量。