变量提升如何理解?var 和 function提升有什么区别?请问大家了
通过var定义(声明)的变量,在定义语句之前就可以访问的到,值为undefined ; 通过function声明函数,在之前就可以直接调用,值为:函数定义(对象)
函数提升优先级大于变量提升优先级
可以看下这篇文章
https://blog.csdn.net/lancecool/article/details/116783119
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
console.log("str1", str1);
var str1 = "字符串";
// 上面没有报错,输出undefined,实际上就是相当于下面这样,就是变量提升
var str2;
console.log("str2", str2);
str2 = "字符串";
var str3 = 1;
function print() {
console.log("第一次输出str3", str3); // 将print函数内str3变量提升
var str3 = 2;
}
print();
console.log("第二次输出str3", str3);
// 输出1,是因为es5中非为 全局作用域和函数(局部)作用域
// print形成一个函数作用域,第二次输出str3找不到print里面
</script>
</body>
</html>