JS (global scope)

1. Global function scope (put variable declarations and function declarations in front)

Scope: The scope in which a piece of data can be used. Generally speaking, data used in a piece of program code is not always valid/available, and the scope of code that limits the availability of this data is the scope of the name. The use of scope improves the locality of program logic, enhances program reliability, and reduces name conflicts.

In variable (data) js, there are two scopes of variables, one is the global scope (global variable), the other is the local scope (local variable), and whether a variable is a global variable or a local variable mainly depends on the variable declaration Location. A variable declared inside a function is a local variable of the function.

Global Scope - Variables defined outside a function can be accessed anywhere Has global scope Variables defined without var have global scope All properties on the window object have global scope Functions not declared inside any function have global scope Global scope Local scope --- Only variables defined inside a function using var, and functions declared inside a function using function, have local scope

See scope

Output: zhangsan

equivalent to

2. Execution can also be done before the definition

 this and arguments will have their values ​​determined before execution

scope chain

[[Scopes]] : Scope When we declare a function, the function will create a property at the same time. This property is [Scopes] , and the variables we declare in this function will be stored in the [[Scopes] of this function. ] The search rules for variables and functions in the attribute: When we call a piece of data, js will first search in the current scope. If it is not found, it will find the parent's scope upward. If it is in the parent's scope If you can't find it in the window, continue to look up until the scope of the window. If it is not found in the window, it will report an error

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325247536&siteId=291194637