Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

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

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; } What is a named/anonymous function expression?(什么是命名/匿名函数表达式?) What is a declared function?(什么是声明函数?) How do browsers deal with these constructs differently?(浏览器如何不同地处理这些结构?) What do the responses to a similar question ( var functionName = function() {} vs function functionName() {} ) not get exactly right?(对类似问题( var functionName = function(){}与function functionName(){} )的回答有什么不正确的答案?)   ask by Faisal Vali translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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中的错误,尽管不再发生。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...