scope

Scope: local scope, global scope

var num1 = 1;
var num2 = 2;

const fun1 = (n1,n2) => {
    var num3 = 3;
    n1 = 10;
    n2 = 20;
    console.log(num1,num2,num3,n1,n2);  // 1 2 3 10 20
}
fun1(num1,num2);
console.log(num1,num2);  // 1 2
console.log(num3); // error: num3 is not defined
console.log(n1,n2);
Copy the code

Print the result

1 2 3 10 20 1 2 Error: num3 is not defined // The following error message will not be displayed because the previous error message will prevent the following code from executing error: n1 is not defined error: n2 is not definedCopy the code

conclusion

  • Objects that can be accessed anywhere have a global scope

    In the example above, num1, num2 are globally scoped variables, and external variables can be accessed from within the functionCopy the code
  • Variables are declared in functions and are local scopes

    In the example above, num3, n1, and n2 are locally scoped variables and cannot be accessed from outside the functionCopy the code

Reference type passing of the scope

function fun2(name,age){
    this.name = name;
    this.age = age;
    }
const zs = new fun2('zs',18);
console.log(zs.name);  // zs

const fun3 = (p) => {
    p.name = 'ls';
    p = new fun2('ww',20);
    console.log(p); // fun2 {name: 'ww', age: 20}
    p.name = 'ml';
    console.log(p.name); // ml
   }
fun3(zs);
console.log(zs.name); // ls
console.log(zs); // fun2 {name: 'ls', age: 18}
Copy the code

Print the result

zs
fun2 {name: 'ww', age: 20}
ls
fun2 {name: 'ls', age: 18}
Copy the code

conclusion

  • If the heap memory address is changed, the external cannot read the modified properties

    Inside func3: The name modified before new func2 is valid (externally desirable to read the name) and the name modified after new fun2 is the name of the internal addressCopy the code