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

第32题(2019-09-03):考察作用域的一道代码题 #34

Open
qappleh opened this issue Sep 3, 2019 · 1 comment
Open

第32题(2019-09-03):考察作用域的一道代码题 #34

qappleh opened this issue Sep 3, 2019 · 1 comment
Labels

Comments

@qappleh
Copy link
Owner

qappleh commented Sep 3, 2019

以下代码会输出什么?

var a = 10;
(function () {
	console.log(a)
	a = 5
	console.log(window.a)
	var a = 20
	console.log(a)
})()  
@qappleh
Copy link
Owner Author

qappleh commented Sep 4, 2019

依次输出:undefined -> 10 -> 20

解析:

在立即执行函数中,var a = 20; 语句定义了一个局部变量 a,由于js的变量声明提升机制,局部变量a的声明会被提升至立即执行函数的函数体最上方,且由于这样的提升并不包括赋值,因此第一条打印语句会打印undefined,最后一条语句会打印20。

由于变量声明提升,a = 5; 这条语句执行时,局部的变量a已经声明,因此它产生的效果是对局部的变量a赋值,此时window.a 依旧是最开始赋值的10,

@qappleh qappleh added the js label Nov 27, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant