devStandard/docs/learning/3-js/2.2-变量提升和函数声明提升.md
2025-03-29 14:35:49 +08:00

80 lines
1.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# var变量提升和函数声明提升
## var变量提升
> * var关键字声明的变量无论实际声明的位置在何处都会被视为声明在函数的顶部如果声明不在任意函数内则视为在全局作用域的顶部
> * JavaScript引擎的工作方式是先预解析代码 获取所有被声明的变量和函数声明,然后再一行一行地运行,这就使所有变量声明的语句,都会被提升到代码的头部,这就是变量提升
```js
a = 2
console.log(a)
var a = 1
console.log(a)
```
实际
```js
var a // var声明被提前到顶部, 此时值是undefined
a = 2
console.log(a)
a = 1 // 赋值还是在原来的位置
console.log(a)
```
## 函数声明提升
函数定义有三种: 声明式, 函数式, 构造函数
声明式: `function fn (){}`
函数式: `const fn = (){}`
构造函数: `const fn = new Function("a","b","return a+b");`
其中, 声明式有提升效果
> 函数声明语句将会被提升到外部脚本或者外部函数作用域的顶部
```js
f('superman');
function f(name){
console.log(name);
}
```
实际
```js
function f(name){
console.log(name);
}
f('superman');
```
例子:
```js
var getName = function(){
console.log(2);
}
function getName (){
console.log(1);
}
getName(); // 输出2
```
实际
```js
function getName(){ //函数声明提升到顶部
console.log(1);
}
var getName; //变量声明提升
getName = function(){ //变量赋值依然保留在原来的位置
console.log(2);
}
getName(); // 最终输出2
```