Global and private variables

# 2.

The distinction between private and global variables must be memorized

In a private scope, only the following two cases are private variables

A: Declared variables (with var/function)

B: Parameters are also private variables

The rest are not private variables and need to be looked up based on scope-chain mechanisms

var a=12, b=13, c=14; Function fn(a){console.log(a,b,c) var b=c=a=20 console.log(a,b,c)} fn(a) console.log(a,b,c) {function fn(a){console.log(a,b,c) var b=c=a=20 console.log(a,b,c)} fn(a) console.log(a,b,c) Value), passing the value 12 of the global variable a as an argument to the function parameter =>fn(12). Console. log(a,b,c) =>(12,undefined,14); Log (a,b,c) =>(20, 20, 20) console.log(a,b,c) =>(12,13,20) The global variable has been changed to 20 and if you don't understand that take a look at the whole implementation. Var a; var a; var b; Var c [var c] fn= XXX... A =12, b=13,c=14 function fn... This line is skipped by the machine, because the variable promotion phase has already been declared and defined, so the machine will not repeat the operation. Next, fn(a) (argument: value in parentheses) => is executed, passing the value of global variable A, 12, as an argument to the function parameter =>fn(12). Var /function () {var/function (); var/function () {var/function (); var/function (); Parameters are also private variables, and the rest are not private variables, which need to be looked up based on the scope chain mechanism. A and b are private variables that have nothing to do with the outside, but since a is a parameter assignment, A will pass 12 in, b will pass undefined, c will be a global variable, and 14 will be output to the parent window. 14) var b=c=a=20 var b=20 c=20 var b=20 c=20Copy the code
Var ary=[12,23] function fn(ary){console.log(ary); / / = > [12, 10] ary [0] = 100; ary=[100]; ary[0]=0; console.log(ary); //=>[0] } fn(ary); console.log(ary); / / = > [June 100]Copy the code

Combines private/global, variable promotion/parameter assignment, scope, primitive and reference types

The best way is to draw a picture !!!!