函数提升和返回语句 [英] Function hoisting and the return statement

查看:44
本文介绍了函数提升和返回语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这个(为了示例而减少)函数可以顺利运行,但由于 fn2 未定义而失败:

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:

void function(){
    var var1 = fn1();
    var var2 = fn2();

    function fn1(){};

    return function fn2(){};
}();

return 语句如何从提升中排除 fn2 的函数表达式?

How does the return statement exclude the function expression for fn2 from hoisting?

推荐答案

仅提升使用函数声明创建的函数.return function fn2(){}; 中的函数是使用(命名)函数表达式创建的,因此没有被提升.

Only a function created with a function declaration is hoisted. The function in return function fn2(){}; is created with a (named) function expression so is not hoisted.

函数的评估方式取决于上下文.语句中的任何函数(例如 return 语句)都被解析为函数表达式.另一个例子是在 IIFEs 中使用括号:括号充当分组运算符,确保括号的内容作为表达式求值.

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. 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.

可以在 Kangax 的优秀文章中找到很多关于此的信息:

Lots of information about this can be found in Kangax's excellent article:

http://kangax.github.io/nfe/

这篇关于函数提升和返回语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆