当前位置:网站首页>函数提升和变量提升
函数提升和变量提升
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()......的声明之前,但是因为它是重复的声明(因此被忽略了)因为当有重复声明时,函数声明会优先于变量声明被提升。
边栏推荐
- Scientific research reagent DMPE-PEG-Mal dimyristoylphosphatidylethanolamine-polyethylene glycol-maleimide
- 知识工程作业2:知识工程相关领域介绍
- 小程序 van-cell 换行能左对齐问题
- Amazon sellers how to improve the conversion
- subprocess.CalledProcessError: Command ‘pip install ‘thop‘‘ returned non-zero exit status 1.
- Debian 10 NTP 服务配置
- AttributeError: Can't get attribute 'SPPF' on
- ThunderBirde无法登录问题、pycharm调试一直收集数据、RuntimeError: CUDA error: device-side assert triggered等疑难杂症解决
- Usage of JOIN in MySQL
- 【博学谷学习记录】超强总结,用心分享 | 软件测试 接口测试基础
猜你喜欢
【手把手带你学nRF52832/nRF52840 · (1)开发环境搭建】
【我的创作纪念日】 3周年
磷脂-聚乙二醇-叠氮,DSPE-PEG-Azide,DSPE-PEG-N3,MW:5000
parser = argparse.ArgumentParser()解析
STM32 CAN过滤器
[Basic Tutorial of Remote Control Development 1] Crazy Shell Open Source Formation Drone-GPIO (Remote Control Indicator Light Control)
亚马逊卖家怎么提升转化率
磷脂-聚乙二醇-酰肼,DSPE-PEG-Hydrazide,DSPE-PEG-HZ,MW:5000
Chapter 10 Clustering
String comparison size in MySQL (date string comparison problem)
随机推荐
mysql卸载详细教程
C语言 void和void *(无类型指针)
【我的创作纪念日】 3周年
AttributeError: Can‘t get attribute ‘SPPF‘ on <module ‘models.common‘ from ‘/yolov5-5.0/models/commo
sh: 1: curl: not found
化学试剂磷脂-聚乙二醇-羟基,DSPE-PEG-OH,DSPE-PEG-Hydroxyl,MW:5000
Scientific research reagent DMPE-PEG-Mal dimyristoylphosphatidylethanolamine-polyethylene glycol-maleimide
UserWarning: torch.meshgrid: in an upcoming release, it will be required to pass the index ing argu
第一篇博客
【 application 】 life many years of operations, what turned scored 12 k + annual bonus salary?
Redis简单学习笔记
The difference between the knowledge question and answer session with the knowledge
js 数组去重的常用方法
mysql创建表
parser = argparse.ArgumentParser()解析
docker 安装 sqlserver中的坑点
【装机】老毛桃的安装及使用
mysql8.0安装教程与配置(最详细)操作简单
C语言中关于2的n次方求值问题(移位运算)
querystring模块