Home >Web Front-end >JS Tutorial >Things about global variables and local variables_Basic knowledge

Things about global variables and local variables_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:43:421400browse

Variables are very familiar to students who learn js and programming languages. I won’t elaborate on the official definition here. There are too many online. Today we will understand them from life

1. What are variables?
For example:
A water glass contains water, and the water glass is a variable;
A bottle of beer, and the beer bottle is a variable;
A variable is a carrier, a medium

2. Define variables
var a=12; //typeof a=Numer
var a='aaa' //typeof a =string
This shows the type of the variable Depends on what value is paid to him
For example, a cup filled with water is a water glass, filled with wine is a wine glass, and filled with vinegar is a vinegar bottle

3. Variable type
Variable types are divided into: basic types and reference types
Basic types are divided into: Number (numeric type), String (string type), Boolean (Boolean type), Undefined (undefined), Null
Reference types: Most of them are Objects
Basic type values ​​are simple data stored in stack memory, and they occupy a location in memory;
Reference type values ​​are objects stored in heap memory. What is stored in the stack memory is the address, which points to the object in the heap memory

1. Local variables

Copy code The code is as follows:


functionaaa()
{
vara=10;
}
functionbbb()
{
alert(a)
}
aaa()
bbb()


Running result: Error: "a" is undefined, a is a local variable, it only belongs to function aaa, not function bbb
2. Global variable 1
Copy code The code is as follows:


vara
functionaaa()
{
vara=10;
}
functionbbb()
{
alert(a)
}
aaa()
bbb( )


Run result: Undefined pops up. This is also one of the types of variables, but it is an undefined type. It is not the same as the first The type of an undefined
variable is determined by the value assigned to the variable. At this time, a in the bbb function is a global variable. Although it is var, it does not specify a value, so it is undefined
3. Global variable 2
Copy code The code is as follows:


vara
functionaaa()
{
a=10;
}
functionbbb()
{
alert(a)
}
aaa()
bbb()


Running result: 10, a is a global variable and passed The function aaa is assigned a value - 10
ps: We often call undefined as undefined, both through 1 and 2. Can we say undefined≠undefined?
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn