在以下示例中,我将一个数字添加到 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
谁能帮我理解结果不是 1function
吗?我知道如果块没有自己的范围,所以不知道为什么在圆括号中该函数在圆括号之外不可见.
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.
这篇关于函数的类型没有返回正确的值但未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!