Variables declared in the function

In the javascript language, the variables declared in the function are created once the function is executed, and will be destroyed when the function is executed.

<script>
        function getName () {
    
    
            var name = "凡夫俗子";
            console.log("函数体访问",name)
        }
        getName()
       ert(name)
    </script>

The variable name is defined using var in the function. When the function is called, the variable is created and assigned a value. After that, this variable will be destroyed immediately, so the next line of code in the example will cause an error.
Insert picture description here
Insert picture description here

However, you can omit the var operator as follows to create a global variable:

  function getName () {
    
    
            name = "凡夫俗子";
            console.log("函数体访问",name)
        }
        getName()
        alert(name)

Insert picture description here
Insert picture description here
Although omitting the var operator can define global variables, this is not our recommended practice. Because global variables defined in the local scope are difficult to maintain, and if the var operator is deliberately ignored, it will also cause unnecessary confusion because the corresponding variables will not be defined immediately. Assigning a value to an undeclared variable will cause a ReferenceError to be thrown in strict mode

Guess you like

Origin blog.csdn.net/weixin_43131046/article/details/115238480