[英]What are good situations to use function expression instead of function declaration?
I will prefer to use function declaration all the time because I can place the function anywhere on the source file. 我将更喜欢一直使用函数声明,因为我可以将函数放在源文件上的任何位置。 If I use function expression, the function has to be placed at the top of the source file.
如果使用函数表达式,则必须将函数放在源文件的顶部。
Are there good situations to use function expression instead of function declaration? 是否存在使用函数表达式而不是函数声明的良好情况?
//Function declaration
function foo() { return 5; }
//Anonymous function expression
var foo = function() { return 5; }
All variables declarations are hoisted on the top of the scope and all function definitions are as well hoisted on the top of the scope. 所有变量声明都放在作用域的顶部,所有函数定义也都放在作用域的顶部。 Therefore
因此
console(foo()); // prints foo
function foo(){return 'foo'};
but 但
console(foo()); // complain foo is not function, it is undefined
var foo = function(){return 'foo'};
the second example is identical to this: 第二个示例与此相同:
var foo;
console.log(foo());
foo = function(){}
The reasons for using the second expression would stem from your programming logic. 使用第二个表达式的原因将源于您的编程逻辑。 for example:
例如:
var foo = MY_ENV_VAR ? function(){return true} : function(){return false}
or run the following example for better understanding: 或运行以下示例以更好地理解:
var bar;
if (true) {
function foo(){return 'foo'};
bar = function(){return 'hey'};
} else {
function foo(){return 'another'};
bar = function(){return 'bar'};
}
console.log(foo());
console.log(bar());
the first log will be another
because JS compiler puts the function declaration on the top of the scope and the second declaration just overwrites the first one. 第一个日志将是
another
日志,因为JS编译器将函数声明放在作用域的顶部,而第二个声明只是覆盖了第一个日志。 While the second log outputs the result of the function assigned in the if statement , which will be hey
. 当第二个日志输出if语句中分配的函数的结果时,它将为
hey
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.