从条件语句提升 javascript 中的函数
Function hoisting in javascript from condition statement
为什么
var y = 1;
if (function f(){}) {
y += typeof f;
}
console.log(y); // 1undefined
在 运行 代码之前我想它会是 1function
我想函数提升 f 的后面应该对所有代码都是可见的。你能提供link这样的行为描述吗?
P.S> 在博客 post 我找到这个例子的地方有解释
The output would be 1undefined. The if condition statement evaluates using eval, so eval(function f(){}) returns function f(){} (which is true). 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.
但这并没有使情况更加明朗
这里的混淆是语法 function fName() {}
不明确并且取决于上下文。
单独来看,它是一个函数声明,因此被提升了。但在某些情况下,它是一个(命名的)函数表达式,因此不是。
这就是为什么您会看到 IIFE 声明为 (function() {..})()
或 !function() {..}()
以强制它们成为函数表达式而不是声明。
关于命名函数表达式的重要一点是它们的名称本质上是函数本身的局部名称,并且在该函数之外无法访问。这就是 += f
在您的代码中附加 undefined
的原因。
当然,这一切都是毫无意义的。为什么头脑正常的人会写这样的代码?所以我想留给你们:https://youtu.be/RAA1xgTTw9w :)
为什么
var y = 1;
if (function f(){}) {
y += typeof f;
}
console.log(y); // 1undefined
在 运行 代码之前我想它会是 1function
我想函数提升 f 的后面应该对所有代码都是可见的。你能提供link这样的行为描述吗?
P.S> 在博客 post 我找到这个例子的地方有解释
The output would be 1undefined. The if condition statement evaluates using eval, so eval(function f(){}) returns function f(){} (which is true). 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.
但这并没有使情况更加明朗
这里的混淆是语法 function fName() {}
不明确并且取决于上下文。
单独来看,它是一个函数声明,因此被提升了。但在某些情况下,它是一个(命名的)函数表达式,因此不是。
这就是为什么您会看到 IIFE 声明为 (function() {..})()
或 !function() {..}()
以强制它们成为函数表达式而不是声明。
关于命名函数表达式的重要一点是它们的名称本质上是函数本身的局部名称,并且在该函数之外无法访问。这就是 += f
在您的代码中附加 undefined
的原因。
当然,这一切都是毫无意义的。为什么头脑正常的人会写这样的代码?所以我想留给你们:https://youtu.be/RAA1xgTTw9w :)