Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

变量提升 #5

Open
dvlin-dev opened this issue Apr 3, 2022 · 0 comments
Open

变量提升 #5

dvlin-dev opened this issue Apr 3, 2022 · 0 comments
Labels
js JavaScript

Comments

@dvlin-dev
Copy link
Owner

dvlin-dev commented Apr 3, 2022

console.log("a",a)
console.log("fn",fn)
console.log("fn1",fn1)
console.log("fn2",fn2)
function fn(){
  console.log(111)
}
var fn1 = function(){
  console.log(222)
}
let fn2 = function(){
  console.log(333)
}
var a = 1;

所以应该输出什么

_
.
.
.
.
.
.
.
_
image

原因是因为变量提升
所谓的变量提升,是指在 JavaScript 代码执行过程中,JavaScript 引擎把变量的声明部分和函数的声明部分提升到代码开头的“行为”。变量被提升后,会给变量设置默认值,这个默认值就是我们熟悉的 undefined。

var a = 1;
可以被拆分为:
var a = undefined;
a = 1;
JavaScript代码执行流程 分为 编译执行两个部分
在编译阶段,变量和函数会被存放到变量环境中,变量的默认值会被设置为 undefined;
var a = undefined;

@dvlin-dev dvlin-dev added the js JavaScript label Apr 5, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests

1 participant