Global scope
- Created when the page is opened, destroyed when closed.
- In the global scope has a global object window, it can be used directly. Created by the browser, you can use the page.
- Global variables created in the role, will generate as a property of the window object. var a = 10, available window.a call. Create a function is generated as a method of window.
var a = 10;
console.log(window.a) //等于console.log(a)
function fun() {}
Variable declaration in advance
- Variables declared using the var keyword, it will be declared before any code is executed (but not assigned).
- If you do not use the var keyword when declaring a variable, the variable will not be declared in advance.
Var keyword:
console.log(a) // undefined
var a = 123;
Equivalent to:
var a // 声明
console.log(a) // undefined
a = 123; //赋值
Do not use the var keyword to declare variables:
console.log(a) // Uncaught ReferenceError: a is not defined
a = 123
Function declaration in advance
- Created with the function declarations in the form of a function (fun1) it will then be created before any code is executed, so you can call before the function declaration.
- Use create function expression of the function is not declared in advance, it can not be declared before the call.
fun1() // 控制台打印 "我是fun1"
console.log(fun2) // undefined
fun2() // Uncaught TypeError: undefined is not a function(fun2不是函数)
function fun1() { // 函数声明,会被提前创建
console.log('我是fun1')
}
var fun2 = function() { // 函数表达式,不会提前创建
console.log('我是fun2')
}
Function scope
- Create a function scope when the function is called function is completed destroyed.
- Each call to the function will create a new function scope, independent of each other.
- In the scope function can access variables global scope.
- Global scope can not access to the function scope variables.
var a = 10
function fun() {
var b = 10
console.log(a)
}
fun() // 10
console.log(b) // Uncaught ReferenceError: b is not defined
- When the manipulated variable scope function, its role is now looking domain, there are used directly, without the up to find a scope.
var a = 10
function fun() {
var a = '函数中a'
console.log(a) // 函数中a
}
fun() // 10
- In the scope function declaration also advance features variable declared using the var keyword will be (will function declaration) declaration before any code is executed in the function.
var a = 10
function fun3() {
console.log(a) // undefined (var关键字变量声明提前)
var a = 20
}
- Variables do not use var declared in a function, will become global variables.
var c = 10
function fun5() {
console.log(a) // undefined (var关键字变量声明提前)
c = 20 // 这里改变了全局的c
d = 100 // d 没有使用var关键字则会设置为全局变量
}
console.log(c) // 20
console.log(d) // 100
- Parameter corresponds to the function defined scope declared variables.
var e = 23
function fun6(e) {
console.log(e) // undefined
}
fun6()