Valid JavaScript Variable Scope Item 8-9 Globals and Locals, scopeglobals
This series serves as the Reading Notes for objective JavaScript.
Item 8: fewer global objects
Important:
- Global Objects can bring convenience, but experienced programmers can avoid them. Because it brings potential risks of name conflicts
- Global variables are the bond between different modules. global variables can only be used between modules to access functions provided by each other.
- Do not use global variables when using local variables.
- In browser, this keyword will point to the global window object
- Two methods are used to change the global object. The var keyword is used to declare and set attributes for the Global Object (through the this keyword)
- The Feature Detection of the current running environment is detected through the Global Object. For example, if (this. JSON) to determine whether the current running environment supports JSON
Summary:
- Avoid declaring global variables
- Use local variables whenever possible
- Avoid adding attributes to Global Objects
- Use global variables for Feature Detection
Item 9: always declare local variables
Important:
- Implicit global variables are more difficult than global variables. For example:
function swap(a, i, j) { temp= a[i]; // global a[i]= a[j]; a[j]= temp;}
The above temp is implicitly declared as a global variable.
- Use the lint tool to check whether global variables are implicitly declared in JavaScript code.
Summary:
- Always remember to declare local variables with the var keyword
- Use the lint tool to ensure that no global variables are implicitly declared.
In python, why do the parameters in eval (source [, globals [, locals]) Follow '[' or ']'?
The parameter with [] is optional.