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.(如果您改为调用函数声明,它将始终有效,因为在加载所有声明之前,无法调用任何代码。)
Example: Function Expression(示例:函数表达式)
alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; }
Example: Function Declaration(示例:函数声明)
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; }
var foo = function foo() { return 5; }
is really the same as the other two.(var foo = function foo() { return 5; }
实际上与其他两个相同。) It's just that this line of code used to cause an error in safari, though it no longer does.(只是这行代码曾经导致safari中的错误,尽管不再发生。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…