1、变量提高javascript
在ES6以前,JavaScript没有块级做用域(一对花括号{}即为一个块级做用域),只有全局做用域和函数做用域。变量提高即将变量声明提高到它所在做用域的最开始的部分。上个简历的例子如:java
1
2
3
4
5
6
7
8
9
10
|
console.log(global);
// undefined
var
global =
'global'
;
console.log(global);
// global
function
fn () {
console.log(a);
// undefined
var
a =
'aaa'
;
console.log(a);
// aaa
}
fn();
|
之因此会是以上的打印结果,是因为js的变量提高,实际上上面的代码是按照如下来执行的:函数
1
2
3
4
5
6
7
8
9
10
11
12
|
var
global;
// 变量提高,全局做用域范围内,此时只是声明,并无赋值
console.log(global);
// undefined
global =
'global'
;
// 此时才赋值
console.log(global);
// 打印出global
function
fn () {
var
a;
// 变量提高,函数做用域范围内
console.log(a);
a =
'aaa'
;
console.log(a);
}
fn();
|
2、函数提高spa
js中建立函数有两种方式:函数声明式和函数字面量式。只有函数声明才存在函数提高!如:code
1
2
3
4
|
console.log(f1);
// function f1() {}
console.log(f2);
// undefined
function
f1() {}
var
f2 =
function
() {}
|
只因此会有以上的打印结果,是因为js中的函数提高致使代码其实是按照如下来执行的:blog
1
2
3
|
function
f1() {}
// 函数提高,整个代码块提高到文件的最开始<br> console.log(f1);
console.log(f2);
var
f2 =
function
() {}
|
结语:基本上就是这样,要熟练掌握的话能够多作些练习,test:ip
1
2
3
4
|
console.log(f1());
console.log(f2);
function
f1() {console.log(
'aa'
)}
var
f2 =
function
() {}
|
1
2
3
4
5
6
|
(
function
() {
console.log(a);
a =
'aaa'
;
var
a =
'bbb'
;
console.log(a);
})();
|