background
Js scope is divided into global scope and local scope, there is no block-level scope. Scope is the accessible range of variables and functions.
Knowledge of anatomy
A local scope can only be accessed within a scope such as a variable within a function. The global scope can access variables anywhere in the script tag.
The sample
var name = 'little red' // Red is the global scope
var age = 20
function test(){
var name = 'Ming' // Xiaoming is a local scope
console.log(name) // The print result is Xiaoming
console.log(age) // Prints 20
}
test()
console.log(name) // Prints a little red
Copy the code
From the example of name variable, it can be seen that the global scope variable and the local scope variable do not conflict, and the global scope cannot access the name in the local function body. But inside the function you can get the age of the global scope.
How to declare global and local variables
Variables in js that are not declared by val are automatically global.
var name = 'little red' // Red is the global scope
function test(){
var name = 'Ming' // Xiaoming is a local scope
hobby = 'basketball' // Local variables that are not declared by var
console.log(name) / / xiao Ming
}
test()
console.log(name) // Prints a little red
console.log(hobby) // Print the result as basketball
Copy the code
The function variable Hobby is apparently called outside the function. Variables in a local scope are not normally accessible outside the local scope, so we verify that variables not declared by VAR are global variables.
The scope chain
Scopes can be nested, and if the target variable is not accessible within the scope, it will be looked up level by level.
var name = 'little red'
tow()
function tow(){
var name = 'white'
three()
function three(){
var name = 'the little green'
console.log(name) // The result is small green
}
}
}
one()
//-----------
var name = 'little red'
tow()
function tow(){
var name = 'white'
three()
function three(){
console.log(name) // The result is small white
}
}
}
one()
Copy the code
Summarize your summary and type it into the comment section to improve your understanding.