JavaScript 中定义函数用 var foo = function () {} 和 fu
网络编程 2021-07-04 17:33www.168986.cn编程入门
这篇文章主要介绍了JavaScript 中定义函数用 var foo = function () {} 和 function foo()区别介绍,需要的朋友可以参考下
某天写代码突然县道这个问题,顺势总结一波
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()区别介绍,希望对大家有所帮助,如果大家有任何疑问请给我留言,长沙网络推广会及时回复大家的。在此也非常感谢大家对狼蚁SEO网站的支持!
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程