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.
#In JavaScript, variables declared with var actually have scope.
If a variable is declared inside the function body, the scope of the variable is the entire function body, and the variable cannot be referenced outside the function body:
'use strict';function foo () {
var x = 1;
x = x + 1;
}
x = x + 2; // ReferenceError! Unable to reference variable x# outside the function body
'use strict';function foo() { var x = 1;
x = x + 1;
}function bar() {
var x = 'A';
x = x + 'B';
}
##JavaScript Local scope
Variables are declared within the function, and the variables are local scope.
Local variables: can only be accessed inside the function.
// The carName variable cannot be called herefunction myFunction() {
var carName = "Volvo";
// The carName variable can be called within the function
}
Because local variables only act within the function, 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.
Global scope Variables not defined within any function have global scope. In fact, JavaScript has a global object window by default, and variables in the global scope are actually bound to a property of window: 'use strict'; var course = 'Learn JavaScript'; ##alert(course); // 'Learn JavaScript' alert(window. course); // 'Learn JavaScript'<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
<p>全局变量在任何脚本和函数内均可访问。</p>
<p id="demo"></p>
<script>
var carName = "Volvo";
myFunction();
function myFunction()
{
document.getElementById("demo").innerHTML =
"这里是 " + carName;
}
</script>
</body>
</html>
Function parameters
Function parameters only work within the function and are local variables.