理解JavaScript提升和真实性falsy [英] Understanding JavaScript hoisting and truthy & falsy
问题描述
我一直在阅读有关JavaScript吊装的消息。
I've been reading about JavaScript hoisting sometime back.
Ben Cherry的JavaScript范围和提升
关于Dmitry Soshnikov提升的两个词
以及更多关于JavaScript类型的信息 - 强制,真相和错误测试:
真相,平等和JavaScript 和其他一些资源
and, some more about JavaScript type-coercion, truth & false test: Truth, Equality and JavaScript and some other resource
在练习一些时,发现我遗漏了一些关于吊装的重要概念和一个变量'truthy& falsy。
And while practicing some, and found I m missing some important concept about the hoisting and a variable' truthy & falsy.
var foo = 1;
function bar() {
if (!foo) {
alert('inside if');
var foo = 10;
}
}
bar();
o / p:里面如果
怀疑:'foo'值为'1',如果(!foo)
应该评估为 false
并且不应该执行该块(引用来自上述资源:提升仅影响 var
& 函数
声明,但不执行)。但为什么会显示该警报。
如果我直接使用 false
(如下面的no-tricks代码:片段#3所示),则不是这种情况。
Doubt: 'foo' value being '1', if(!foo)
should evaluates to false
and that block should not be executed (quoting from above resources: hoisting affects only the var
& function
declaration, but not the execution). But why is that alert is shown.
This is not the case if I directly use false
(shown in the below no-tricks code: snippet #3)
var foo = 1;
function bar() {
if (!foo) {
alert('inside if');
}
}
bar();
o / p:无输出;意味着控制没有输入'if'block
这是人们可以期待的
o/p: no output; means control not entered 'if' block
This is what one could expect
var foo = 1;
function bar() {
if (false) {
alert('inside if');
var foo = 10;
}
}
bar();
o / p:无输出;意味着控制没有进入'如果'块
这是人们可以期待的
o/p: no output; means control not entered 'if' block
This is what one could expect
有人请澄清。谢谢
推荐答案
对于您的示例1,显示警报,因为您使用的是 var 函数内部的code>和
var
声明被提升到函数的顶部,因此它相当于:
For your example number 1, the alert is shown because you're using var
inside the function and the var
declaration is hoisted to the top of the function, so it is equivalent to:
var foo = 1;
function bar() {
var foo;
if (!foo) {
alert('inside if');
foo = 10;
}
}
bar();
有人可能会得出结论,这些问题提供了令人信服的理由将所有变量明确地声明在功能。
One might conclude that these sorts of issues offer compelling reason to declare all variables explicitly at the top of the function.
这篇关于理解JavaScript提升和真实性falsy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!