如果在if条件中定义了函数,是否可以将其吊起? [英] Is a function hoisted if it is defined within an if condition?

查看:59
本文介绍了如果在if条件中定义了函数,是否可以将其吊起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以假设我有这样的东西

So suppose I have something like this

var x = 1;
   if (function f(){}) {
     x += typeof f;
   }
   x;

这将输出"1undefined".我以为它应该输出"1function",因为函数f(){}应该已经悬挂在if之上.显然不是这样-为什么?我以为函数声明和主体总是被提升到范围的顶部?

This outputs "1undefined". I thought it should have output "1function", because function f(){} should have been hoisted above the if. This is clearly not the case - why? I thought function declarations and bodies were always hoisted to the top of the scope?

推荐答案

悬挂了函数声明.函数表达式 不是.

Function declarations are hoisted. Function expressions are not.

这将创建一个名为 的函数表达式:

This creates a named function expression:

if(function f(){})

除了检查函数表达式是否为真之外,它什么都不做.(函数表达式总是真实的.)

It doesn't do anything except check to see if the function expression is truthy. (Function expressions are always truthy.)

关于命名函数表达式,请参见 https://kangax.github.io/nfe/#named-expr :

Regarding named function expressions, see https://kangax.github.io/nfe/#named-expr:

要记住的一个重要细节是该名称为,仅在新定义函数的范围

此代码在新函数表达式的范围之外 ,因此 f 是未定义的:

This code is outside the scope of the new function expression, and therefore f is undefined:

x += typeof f;

命名函数表达式中,您可以毫无问题地引用其名称:

Within a named function expression, you can refer to its name without a problem:

(function f() {
  alert(typeof f);   //function
})();

alert(typeof f);     //undefined

这篇关于如果在if条件中定义了函数,是否可以将其吊起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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