为什么没有为函数 f
创建引用
if ( function f() { } ) {
console.log( typeof f );
}
// result: undefined
而 分配/设置 变量在 if( )
中工作正常
if ( f = 'assigned' ) {
console.log( typeof f );
}
// result: string
我需要知道第一种情况发生了什么,因为第二种情况按预期工作
有人能解释一下吗?
最佳答案
由于您已将 function f() { }
放在表达式上下文中,因此它是一个命名函数表达式,而不是一个函数声明。
这意味着当它创建一个函数,并且该函数的名称为 f
时,它会在函数(本身) 而不是在创建函数的范围内。
// Global scope
function a() {
// a is a function declaration and creates a variable called a to which the function is assigned in the scope (global) that the declaration appears in
function b() {
// b is a function declaration and creates a variable called a to which the function is assigned in the scope (function a) that the declaration appears in
}
var c = function d() {
// c is a variable in the scope of the function b. The function d is assigned to it explicitly
// d is a function expression and creates a variable called d to which the function is assigned in the scope (function d) of itself
};
}
关于javascript 行为 - 函数表达式与函数声明 - 区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49543214/