温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

var foo = function () {} 与 function foo()在JavaScript 中的区别是什么

发布时间:2021-01-04 15:00:38 来源:亿速云 阅读:242 作者:Leah 栏目:web开发

本篇文章给大家分享的是有关var foo = function () {} 与 function foo()在JavaScript 中的区别是什么,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

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';
};

以上就是var foo = function () {} 与 function foo()在JavaScript 中的区别是什么,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI