当JavaScript变量名称和函数名称相同时会发生什么? [英] What happens when JavaScript variable name and function name is the same?

查看:365
本文介绍了当JavaScript变量名称和函数名称相同时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,在其中声明一个函数,并在其后声明一个与该函数同名的变量:

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),但是如果没有此更改,a将被识别为一个函数.

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.

为什么会这样?

推荐答案

函数是一种对象,是一种 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆