为什么JavaScript函数声明(和表达式)? [英] Why JavaScript function declaration (and expression)?
问题描述
我见过其他人使用以下模式。
I've seen others using the following pattern.
var bar = function foo(){};
console.log(bar); // foo()
console.log(foo); // ReferenceError: foo is not defined
但为什么?如果两者都被宣布,我可以看到这一点,但事实并非如此。原因是什么?
But why? I can see the point if both were declared, but they're not. Why is the reason?
推荐答案
如其他人所述,使用示例中的第一个表单(命名函数表达式)可以帮助调试,虽然最近浏览器中内置开发人员工具的改进,但这个论点变得不那么有说服力了。使用命名函数表达式的另一个原因是,您可以将函数名称用作函数体内的变量,而不是ES5中现在弃用的值 arguments.callee
。
As mentioned by others, using the first form in your example (a named function expression) can help with debugging, although with the recent improvements in built-in developer tools in browsers, this argument is becoming less persuasive. The other reason for using a named function expression is that you can use the function name as a variable within the body of the function rather than the now-deprecated in ES5 arguments.callee
.
然而,命名函数表达式错误且在Internet Explorer中实现有问题< 9,在您定位这些浏览器时通常应该避免使用。有关详细信息,请参见 Juriy Zaytsev关于该主题的优秀文章。
However, named function expressions are incorrectly and problematically implemented in Internet Explorer < 9 and should generally be avoided when you're targeting those browsers. See Juriy Zaytsev's excellent article on the subject for more information.
这篇关于为什么JavaScript函数声明(和表达式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!