Scope and variables in javascript

The scope of javascript: is the accessible scope of variables and functions, that is, the scope controls the visibility and life cycle of variables and functions.

Global scope

1. Variables that are not defined within a function have global scope. 2. JavaScript has a global object window by default , and variables in the global scope are actually tied to an attribute of the window. 3. The built-in properties of the window object all have a global scope.

Local scope

It is defined by a function, and it is only visible inside the function and is called local scope.

Global variable

Variable access comes from different scopes. Variables declared outside the function definition are global variables. Its value can be accessed and modified throughout the program. The variable is not declared in the function (that is, the var keyword is not used), then it is also a global variable.

Local variable

The variables declared in the function are local variables. Because it only works within a function, different functions can use the same variable name. The variables inside the function cannot be accessed outside the function, and the variables outside the function can be accessed inside the function.

Block-level scope (var does not support block-level scope, ES6 introduces let, const can declare variables with block-level scope)

Refers to variables defined in if, switch, and loop statement blocks. Variables cannot be accessed outside the statement block.

Scope vs context

The scope is based on the function, and the context is based on the object.

Guess you like

Origin blog.csdn.net/baidu_39043816/article/details/108450595