JavaScript study notes (5) scope

  • Scope is the function and effect of variables within a certain range
  • Before js scope (es6): global scope, local scope
  • Global scope: the entire script tag, or a separate js file
  • Local scope: inside the function, it has effects and functions inside the function
  • js does not have block scope

1. Global variables

1. Variables declared globally

2. *Special: inside a function, undeclared

        var num = 10  //num是一个全局变量
        function fn(){
            console.log(num)
        }
        fn()
        function fn2(){
            var num1 = 10 //局部变量
            num2 = 20      //全局变量
        }
        fn2()
        // console.log(num1)
        console.log(num2)

2. Block-level scope

js adds block-level scope in es6

        // block scope

        //in java

        if(**){

            int number = 10;

        }

       // The outside can't call num

but in js 

if(5>3){

            var num = 10;

        }

        console.log(num)

3. Scope chain

 Proximity principle: the output of the following code is 20

        //作用域链
        //console.log('作用域链')
        var num = 10
        function fn(){
            var num = 20
            function fun(){
                console.log(num)
            }
            fun()
        }
        console.log('ss');
        fn()

Guess you like

Origin blog.csdn.net/weixin_44400887/article/details/123905659