函数的类型不返回正确值但未定义 [英] typeof of a function not returning correct value but undefined

查看:92
本文介绍了函数的类型不返回正确值但未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,我向 typeof 函数添加了一个数字,但结果为 1undefined 。为什么?

In the following example I am adding a number to the typeof function, but result is 1undefined. why?

var y = 1;
if (function f(){}) {
  y += typeof f;
}
console.log(y);

预期结果:

1function

实际结果:

1undefined

有人可以帮我理解结果不是 1个功能?我知道,如果block没有自己的作用域,那么在圆括号中为什么函数在圆括号之外不可见是没有意义的。

Can someone help me out understanding how the result is not 1function? I know that if block does not have its own scope, so no sense why in round braces the function is not visible outside the round braces.

推荐答案

该函数被评估为函数表达式,因为它位于 if 语句中。因此,它不会被吊起,也不会在其自身的功能主体之外的任何地方可见。 if 语句的内部期望值,因此将其视为表达式。

The function there is being evaluated as a function expression because it's in an if statement. Thus, it doesn't get hoisted, nor is it visible anywhere other than in its own function body. The inside of the if statement is expecting a value, so it's treated as an expression.

仅函数声明得到悬挂并在街区的任何地方都可见。

Only function declarations get hoisted and become visible anywhere in their block.

这篇关于函数的类型不返回正确值但未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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