JavaScript变量名称与函数名称相同 [英] JavaScript variable name same with function name
本文介绍了JavaScript变量名称与函数名称相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
函数a(x){
return x * 2;
}
var a;
警报(a);
为何显示警报
函数a(x){
return x * 2
}
如果我把 var a = 4
,alert显示4
但是像这样 a
会被识别为功能
为什么会发生这种情况?
解决方案
功能是一种对象,它是值类型。
值可以存储在变量(和属性,并作为参数传递给函数等)。
函数声明:
- 创建一个已命名的函数
- 在当前作用域中创建一个与该函数具有相同名称的变量(除非此变量已存在)
- 将该函数赋值给该变量
- 被挂起
var
语句: - 创建当前作用域中具有指定名称的变量(除非已存在此变量)
- 已被挂起
- 不为该变量赋值(除非与赋值运算符一起使用)
您的声明和 var
语句被挂起。其中只有一个值赋给变量 a
。
I have the following code :
function a(x) {
return x * 2;
}
var a;
alert(a);
why alert displays
function a(x) {
return x * 2
}
???? IF I put var a = 4
, alert displays 4
But like this a
will be recognized as a function
Why this is happening?
解决方案
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).
A function declaration:
- Creates a named function
- Creates a variable in the current scope with the same name as the function (unless such a variable already exists)
- Assigns the function to that variable
- Is hoisted
A var
statement:
- Creates a variable in the current scope with the specified name (unless such a variable already exists)
- Is hoisted
- Doesn't assign a value to that variable (unless combined with an assignment operator)
Both your declaration and var
statement are hoisted. Only one of them assigns a value to the variable a
.
这篇关于JavaScript变量名称与函数名称相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文