21 JavaScript Scope & global variables and local variables & variable life cycle

JavaScript Scope:

There are two types of scopes in JavaScript:

  • Local scope
  • Global scope

JavaScript has function scope, each function to create a new scope.

Scope determines the accessibility variables.

  • Internal function defined variable named local variable, the function is not externally accessible, function parameters are local variables.
  • Variables declared outside the function is called global variables, the scope is global, web pages all scripts and functions can access it.

Global Auto:

Variable assignment has not been declared, this variable will automatically become a global variable.

The following carName no use var statement.

<script>
myFunction();
document.getElementById("demo").innerHTML = carName;
function myFunction(){
    carName = "show!";
}
</script>

 

HTML global variables:

HTML, the global scope is a window, it forms a complete JavaScript environment, all global variables belong to the window object.

Therefore, unless intentional, free to create a global variable is not recommended, because it can cover the window variable or function.

Any function can also cover your global variables and functions.

 

JavaScript variables are valid:

  • Valid JavaScript variable starts when it is created
  • Local variables are deleted when the function is completed
  • Global variables are deleted when you close the page

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/ltfxy/p/11837437.html