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

查看:26
本文介绍了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天全站免登陆