简体   繁体   English

下面代码的输出是什么?

[英]What will be the output of the code below?

I'm working on some typical Javascript interview questions and came across this one.我正在处理一些典型的 Javascript 面试问题,并遇到了这个问题。 I'm confused about the answer and the explanation and am wondering if someone could go more in depth and rephrase it.我对答案和解释感到困惑,想知道是否有人可以更深入地重新表述。

What will be the output of the code below?下面代码的输出是什么?

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

Explanation: The output would be 1undefined.说明:输出将是 1undefined。 The if condition statement evaluates using eval, so eval(function f(){}) returns function f(){} (which is true). if 条件语句使用 eval 进行计算,因此 eval(function f(){}) 返回 function f(){} (这是真的)。 Therefore, inside the if statement, executing typeof f returns undefined because the if statement code executes at run time, and the statement inside the if condition is evaluated during run time.因此,在 if 语句内部,执行 typeof f 会返回 undefined 因为 if 语句代码在运行时执行,而 if 条件中的语句是在运行时计算的。

The if condition statement evaluates using eval if 条件语句使用 eval 进行评估

No, not at all.一点都不。 What's inside the if condition is a function expression , and functions (like all Javascript objects) are truthy. if条件中的内容是一个函数表达式,并且函数(如所有 Javascript 对象)是真实的。

Function expressions by themselves (unlike function declarations - that is, function fnName() { ... on their own line) don't result in the function receiving a variable name in the current scope, so f is not seen as a variable name - it's just the name of the function for the function expression.函数表达式本身(与函数声明不同 - 即function fnName() { ...在它们自己的行中)不会导致函数在当前范围内接收变量名,因此f不被视为变量名- 它只是函数表达式的函数名称。

The function expression gets evaluated as truthy inside the if condition, and then is not referenced again.函数表达式在if条件中被评估为真值,然后不再被引用。 There is no variable named f in scope anywhere in the code, so typeof f resolves to undefined ( typeof f will resolve to undefined no matter where it's placed in the code there).在代码的任何位置都没有名为f变量,因此typeof f解析为undefinedtypeof f将解析为undefined无论它放在代码中的什么位置)。

In contrast, if f was a function declaration on its own line, a variable name named f would be created (and therefore typeof f would result in function ):相反,如果f是单独一行的函数声明则会创建一个名为f的变量名(因此typeof f将导致function ):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM