After the following code is executed, it will be undefined
<script type="text/javascript">
if (! 'a' in window) {
var a = 123;
}
console.log(a);
</script>
Explanation 'a' in window
is true
, but when was a declared? Please tell me, thank you!
I changed the code again:
<script type="text/javascript">
if (! 'a' in window) {
a = 123;
}
console.log(a);
</script>
Resulta is not defined
. Since a
has been declared, why is this error reported?
Let’s talk about variable improvement first
No matter whether this code enters the code block of
if
, a still existsBecause when JavaScript is executed, all
variables
and declarative functions defined through var will be promoted to the top of the current scopeVariables created through
var
do not have block-level scope, so they will be promoted to the top of the current function scopeVariables defined in the global scope are all attributes of window
So this code is actually executed in this order
defines
a
, but does not assign a value, so it naturally outputsundefined
About
! 'a' in window
is actually to executenon
on the 'a' string first, and getfalse
, there is nowindow.false
attribute inwindow
, andfalse is returned
, without entering the if code block.You can try the following examples
Second question
After understanding the above, it is very simple. It is useless to define
var
(there is no promotion), andif
is not entered, resulting in a not being defined and an error being reported.There is nothing wrong with this execution,
! 'a' in window
This is false, and then the assignment of a is not executed, and then the console is undefined.If you want the assignment to be executed, just change the judgment condition to
!('a' in window)
.If you still don’t understand, check the operator precedence list.
var
Variable promotion will occur when declaring. During the editing phase, the code declaration is placed at the beginning of the function or code, so it becomes like this:So
a in window
istrue
.As for
The code does not contain
var a
. So there is no problem of variable promotion, so a has not been declared, so! ('a' in window) is true, soa
is123
https://developer.mozilla.org...
You misunderstood the first paragraph
'a' in window
is false!'a' in window
Only when it is truewill it be executed
var a = 123;
Only when a is assigned the value 123 Existence
Panda Sang Zhengjie=_=