[英]Function hoisting and the return statement
I would expect this (reduced for the sake of example) function to run without a hitch, but it fails on account of fn2 is not defined
: 我希望此函数(为方便起见而减少)可以顺利运行,但是由于
fn2 is not defined
而失败:
void function(){
var var1 = fn1();
var var2 = fn2();
function fn1(){};
return function fn2(){};
}();
How does the return statement exclude the function expression for fn2
from hoisting? return语句如何从提升中排除
fn2
的函数表达式?
Only a function created with a function declaration is hoisted. 仅提升使用函数声明创建的函数。 The function in
return function fn2(){};
return function fn2(){};
is created with a (named) function expression so is not hoisted. 使用(命名的)函数表达式创建的,因此不会被吊起。
How a function is evaluated is dependent on context. 如何评估函数取决于上下文。 Any function within a statement (such as a return statement) is parsed as a function expression.
语句(例如return语句)中的任何函数都将解析为函数表达式。 Another example is the use of parentheses in IIFEs : the parentheses act as a grouping operator, ensuring that the contents of the parentheses are evaluated as an expression.
另一个示例是在IIFE中使用括号:括号充当分组运算符,确保将括号的内容作为表达式求值。
Lots of information about this can be found in Kangax's excellent article: 可以在Kangax的出色文章中找到许多有关此的信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.