JavaScript中的函数表达式与声明有什么区别? [英] What is the difference between a function expression vs declaration in JavaScript?

查看:110
本文介绍了JavaScript中的函数表达式与声明有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码行之间有什么区别?

What is the difference between the following lines of code?

//Function declaration
function foo() { return 5; }

//Anonymous function expression
var foo = function() { return 5; }

//Named function expression
var foo = function foo() { return 5; }




  • 什么是命名/匿名函数表达式?

  • 什么是声明的函数?

  • 浏览器如何以不同方式处理这些结构?

  • 对类似的响应是什么?问题( var functionName = function(){} vs function functionName(){} )不完全正确?

    What do the responses to a similar question (var functionName = function() {} vs function functionName() {}) not get exactly right?

    推荐答案

    它们实际上非常相似。你如何称呼它们完全相同。不同之处在于浏览器如何将它们加载到执行上下文中。

    They're actually really similar. How you call them is exactly the same.The difference lies in how the browser loads them into the execution context.

    函数声明在执行任何代码之前加载。

    Function declarations load before any code is executed.

    只有当解释器到达那行代码时才加载函数表达式。

    Function expressions load only when the interpreter reaches that line of code.

    所以如果你试图在之前调用一个函数表达式它已加载,你会收到错误!如果你调用一个函数声明,它将始终有效,因为在加载所有声明之前不能调用任何代码。

    So if you try to call a function expression before it's loaded, you'll get an error! If you call a function declaration instead, it'll always work, because no code can be called until all declarations are loaded.

    示例:函数表达式

    alert(foo()); // ERROR! foo wasn't loaded yet
    var foo = function() { return 5; } 
    

    示例:功能声明

    alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
    function foo() { return 5; } 
    



    至于问题的第二部分:


    As for the second part of your question:

    var foo = function foo(){return 5; } 与其他两个实际上是一样的。只是这行代码用于导致safari中的错误,尽管它不再存在。

    var foo = function foo() { return 5; } is really the same as the other two. It's just that this line of code used to cause an error in safari, though it no longer does.

    这篇关于JavaScript中的函数表达式与声明有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆