Why typeof
of b
is undefined in the below code?
为什么在下面的代码中未定义b的typeof?
var b = function() {}
var a = function() {
var b = b
console.log('typeof function_b:', typeof b)
}
a()
2 个解决方案
#1
2
Because you're initialising a new variable inside the a
function scope with the declaration var b
.
因为您使用声明var b在函数作用域内初始化一个新变量。
var b
gets initialised and ran before the value gets assigned (b = b
), so it is assigning the just-initialised empty value to itself.
var b在赋值(b = b)之前初始化并运行,因此它将刚刚初始化的空值赋给自身。
To alter the output, you can just skip the var
declaration and typeof b
outputs "function":
要改变输出,您可以跳过var声明和typeof b输出“function”:
var b = function() {}
var a = function() {
b = b;
console.log('typeof function_b:', typeof b); // Outputs "function"
}
a();
#2
0
That's because the variable first get declared (var b
), and then assigned b = b
. After declaring it, it is undefined
in that scope, so you're assigning undefined
to it.
那是因为变量首先被声明(var b),然后被赋值b = b。在声明它之后,它在该范围内是未定义的,因此您要为其分配undefined。
#1
2
Because you're initialising a new variable inside the a
function scope with the declaration var b
.
因为您使用声明var b在函数作用域内初始化一个新变量。
var b
gets initialised and ran before the value gets assigned (b = b
), so it is assigning the just-initialised empty value to itself.
var b在赋值(b = b)之前初始化并运行,因此它将刚刚初始化的空值赋给自身。
To alter the output, you can just skip the var
declaration and typeof b
outputs "function":
要改变输出,您可以跳过var声明和typeof b输出“function”:
var b = function() {}
var a = function() {
b = b;
console.log('typeof function_b:', typeof b); // Outputs "function"
}
a();
#2
0
That's because the variable first get declared (var b
), and then assigned b = b
. After declaring it, it is undefined
in that scope, so you're assigning undefined
to it.
那是因为变量首先被声明(var b),然后被赋值b = b。在声明它之后,它在该范围内是未定义的,因此您要为其分配undefined。