JavaScript 中定义函数用 var foo = function () {} 和 function foo()区别介绍
作者:归去来兮-不如去兮 时间:2024-04-16 09:26:51
某天写代码突然县道这个问题,顺势总结一波
JavaScript 函数和变量声明的“提前”(hoist)行为
简单的说 如果我们使用 匿名函数
var a = {}
这种方式, 编译后变量声明a 会“被提前”了,但是他的赋值(也就是a)并不会被提前。
也就是,匿名函数只有在被调用时才被初始化。
如果使用
function a () {};
这种方式, 编译后函数声明和他的赋值都会被提前。
也就是说函数声明过程在整个程序执行之前的预处理就完成了,所以只要处于同一个作用域,就可以访问到,即使在定义之前调用它也可以。
看一个例子
function hereOrThere() { //function statement
return 'here';
}
console.log(hereOrThere()); // alerts 'there'
function hereOrThere() {
return 'there';
}
我们会发现alert(hereOrThere)
语句执行时会alert('there')
!这里的行为其实非常出乎意料,主要原因是JavaScript 函数声明的“提前”行为,简而言之,就是Javascript允许我们在变量和函数被声明之前使用它们,而第二个定义覆盖了第一种定义。换句话说,上述代码编译之后相当于
function hereOrThere() { //function statement
return 'here';
}
function hereOrThere() {//申明前置了,但因为这里的申明和赋值在一起,所以一起前置
return 'there';
}
console.log(hereOrThere()); // alerts 'there'
我们期待的行为
var hereOrThere = function () { // function expression
return 'here';
};
console.log(hereOrThere()); // alerts 'here'
hereOrThere = function () {
return 'there';
};
这段程序编译之后相当于:
var hereOrThere;//申明前置了
hereOrThere = function() { // function expression
return 'here';
};
console.log(hereOrThere()); // alerts 'here'
hereOrThere = function() {
return 'there';
};
总结
以上所述是小编给大家介绍的JavaScript 中定义函数用 var foo = function () {} 和 function foo()区别介绍网站的支持!
来源:https://www.cnblogs.com/wuvkcyan/archive/2018/02/28/8486381.html
标签:js,var,function
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python正则表达式实现简易计算器功能示例
2021-03-24 16:11:43
SQL Server2000的安全策略
2007-08-06 17:14:00
在pytorch中对非叶节点的变量计算梯度实例
2021-08-26 10:13:53
![](https://img.aspxhome.com/file/2023/2/76852_0s.jpg)
Python用requests库爬取返回为空的解决办法
2021-10-30 04:54:29
![](https://img.aspxhome.com/file/2023/9/124329_0s.jpg)
Python+OpenCV实现旋转文本校正方式
2022-09-29 05:32:27
![](https://img.aspxhome.com/file/2023/7/124747_0s.jpg)
MySQL中InnoDB和MyISAM类型的差别
2008-11-05 13:32:00
在CentOS7下安装Python3教程解析
2021-09-17 16:51:13
![](https://img.aspxhome.com/file/2023/9/131539_0s.png)
sql server 编译与重编译详解
2024-01-14 11:02:59
Python Pygame实战之水果忍者游戏的实现
2021-07-25 03:22:37
![](https://img.aspxhome.com/file/2023/2/135432_0s.png)
MySql逗号拼接字符串查询的两种方法
2024-01-18 18:44:44
如何解决SQLServer占内存过多的问题
2008-12-18 15:01:00
JavaScript版俄罗斯方块Easy Tetris实现原理
2009-07-16 10:25:00
![](https://img.aspxhome.com/file/UploadPic/20097/16/i2009621214419-26s.jpg)
Web2.0电子商务网站的交互设计
2009-05-15 12:08:00
![](https://img.aspxhome.com/file/UploadPic/20095/15/01-80s.jpg)
Python实现Harbor私有镜像仓库垃圾自动化清理详情
2021-02-08 17:09:46
Go并发调用的超时处理的方法
2024-04-28 09:15:40
SQL SERVER 2012新增函数之逻辑函数IIF
2024-01-16 05:39:46
python实现精准搜索并提取网页核心内容
2021-04-07 09:14:04
![](https://img.aspxhome.com/file/2023/5/76955_0s.jpg)
基于Python实现人脸识别和焦点人物检测功能
2021-03-09 10:27:45
![](https://img.aspxhome.com/file/2023/5/107995_0s.jpg)
Python学习小技巧之列表项的排序
2022-03-31 12:06:12
Python 多线程的实例详解
2023-09-24 23:15:04