javascript - 函数字面量和函数关键字声明函数有什么区别?
巴扎黑
巴扎黑 2017-04-11 12:53:02
0
3
369
var add1 = function(a,b){
    return a+b;
}
function add2(a,b){
    return a+b;
}

如图,上面两个函数的声明方式有什么区别吗?

巴扎黑
巴扎黑

reply all(3)
阿神

用函数语句创建的函数add2,函数名称和函数体均被提前,在声明它之前就使用它。
但是使用var表达式定义函数add1,只有变量声明提前了,变量初始化代码仍然在原来的位置,没法提前执行。
运行结果如下:

console.log(add2(1,1)); //输出2
function add2(a,b){
    return a+b;
}
console.log(add1(1,1));  //报错:add1 is not a function
var add1 = function(a,b){
    return a+b;
}
PHPzhong

说一个不容易注意的区别吧
递归的时候

function bar(){
    ......
}

在函数体内可以用bar调用到自己

var foo = function(a,b){
     ......
}

foo则不行

刘奇

声明函数具有函数提升效果,可以在声明函数的代码前执行函数

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!