当前位置:网站首页>函数提升和变量提升
函数提升和变量提升
2022-08-02 03:22:00 【小茹想睡觉】
我们先看两个相似的代码
a = 2;
var a ;
console.log(a);
console.log(a);
var a = 2;
第一个输出的是2
第二个输出值为underfined
大家可能为会好奇这是为什么呢?
下面我们来研究一下
这是因为变量和函数在内的所有声明都会在任何代码被执行前首先被处理
所以第一个代码实际上是这样处理的
var a;
a = 2;
console.log(a);
第二个代码是这样处理的
var a ;
console.log(a);
a = 2;
这个过程就好像变量和函数声明从它们在代码中出现的位置被“移动”到了最上面。这个过程就叫做提升
注意:只有声明本身会被提升,而赋值或其他运行逻辑会留在原地。如果提升改变了代码执行的顺序,会造成非常严重的破坏。函数声明可以提升,函数表达式不可以提升,
函数优先
函数声明和变量声明都会被提升,但是在重复声明的代码中函数会首先被提升,然后才是变量
foo();//1
var foo;
function foo() {
console.log(1);
}
foo = function() {
console.log(2);
}
这个会输出1而不是2,这段代码会被引擎理解成下面格式
function foo(){
console.log(1);
}
foo(); // 1
foo = function(){
console.log(2);
}
这里var foo尽管出现在function foo()......的声明之前,但是因为它是重复的声明(因此被忽略了)因为当有重复声明时,函数声明会优先于变量声明被提升。
边栏推荐
- Deveco studio 鸿蒙app访问网络详细过程(js)
- DSPE-PEG-DBCO Phospholipid-Polyethylene Glycol-Dibenzocyclooctyne A Linear Heterobifunctional Pegylation Reagent
- 知识工程作业2:知识工程相关领域介绍
- 【博学谷学习记录】超强总结,用心分享 | 软件测试 接口测试基础
- The @autowired distinguished from @ the Resource
- The usage of json type field in mysql
- Mysql8.0安装教程
- ssm various configuration templates
- 针对简历上的问题
- 如何查看一个现有的keil工程之前由什么版本的keil IDE编译
猜你喜欢
AttributeError: 'Upsample' object has no attribute 'recompute_scale_factor'
MySQL分库分表
Usage of JOIN in MySQL
Chapter 10 Clustering
mysql中如何查看表是否被锁
小程序 van-cell 换行能左对齐问题
DSPE-PEG-PDP, DSPE-PEG-OPSS, phospholipid-polyethylene glycol-mercaptopyridine supply, MW: 5000
【 application 】 life many years of operations, what turned scored 12 k + annual bonus salary?
每天填坑,精卫填坑第二集,TX1 配置从固态启动,安装Pytorch
化学试剂磷脂-聚乙二醇-羟基,DSPE-PEG-OH,DSPE-PEG-Hydroxyl,MW:5000
随机推荐
The @autowired distinguished from @ the Resource
STM32 CAN过滤器
科研试剂DMPE-PEG-Mal 二肉豆蔻酰磷脂酰乙醇胺-聚乙二醇-马来酰亚胺
【 application 】 life many years of operations, what turned scored 12 k + annual bonus salary?
STM32 触发HardFault_Handler如何查找原因
DSPE-PEG-Silane, DSPE-PEG-SIL, phospholipid-polyethylene glycol-silane modified active group
[Mianjing] Mihayou data development on one side and two sides
第一篇博客
subprocess.CalledProcessError: Command 'pip install 'thop'' returned non-zero exit status 1.
MySQL分页查询的5种方法
MySQL中字符串比较大小(日期字符串比较问题)
nucleo stm32 h743 FREERTOS CUBE MX配置小记录
MySQL分库分表
MySQL8.0与MySQL5.7差异分析
AttributeError: 'Upsample' object has no attribute 'recompute_scale_factor'
3 minutes to take you to understand WeChat applet development
ssm various configuration templates
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boo
C语言 void和void *(无类型指针)
利用 nucleo stm32 f767zi 进行USART+DMA+PWM输入模式 CUBE配置