当 JavaScript 变量名和函数名相同时会发生什么? [英] What happens when JavaScript variable name and function name is the same?
问题描述
我有以下代码,我在其中声明了一个函数,并在它之后声明了一个与该函数同名的变量:
I have the following code, where I declare a function and after it, a variable with the same name as the function:
function a(x) {
return x * 2;
}
var a;
alert(a);
我希望这会提醒 undefined
,但如果我运行它,警报将显示以下内容:
I expected this to alert undefined
, but if I run it, the alert will display the following:
函数a(x){
返回 x * 2
}
function a(x) {
return x * 2
}
如果我为变量赋值(例如 var a = 4
),警报将显示该值(4
),但没有此更改 将被识别为函数.
If I assign a value to the variable (like var a = 4
), the alert will display that value (4
), but without this change a
will be recognized as a function.
为什么会这样?
推荐答案
Functions 是一种 object 是一种 value.
Functions are a type of object which are a type of value.
值可以存储在变量(和属性,并作为参数传递给函数等)中.
Values can be stored in variables (and properties, and passed as arguments to functions, etc).
函数声明:
- 创建一个命名函数
- 在当前作用域中创建一个与函数同名的变量(除非这样的变量已经存在)
- 将函数分配给该变量
- 被吊起来
var
语句:
A var
statement:
- 在当前作用域中创建一个具有指定名称的变量(除非这样的变量已经存在)
- 被吊起来
- 不为该变量赋值(除非与赋值运算符结合使用)
你的声明和 var
语句都被提升了.只有其中一个为变量 a
赋值.
Both your declaration and var
statement are hoisted. Only one of them assigns a value to the variable a
.
这篇关于当 JavaScript 变量名和函数名相同时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!