javascript - Confusion with a function declaration example in Elevation
淡淡烟草味
淡淡烟草味 2017-06-26 10:50:47
0
2
614

"JavaScript Advanced Programming" Chapter 7 Functions, regarding the promotion of function declarations, there is such an example:

if(condition){ function sayHi(){ alert("Hi!"); } } else { function sayHi(){ alert("Yo!"); } }

The original text in the book says:

On the surface, the above code means that when condition is true, use one definition of sayHi(); otherwise, use another definition. In fact, this is invalid syntax in ECMAScript, and the JavaScript engine will try to correct the error and convert it into a reasonable state. But the problem is that browsers are inconsistent in their attempts to correct errors. Most browsers will return the second statement, ignoring condition; Firefox will return the first statement if condition is true. Therefore this usage is dangerous and should not be used in your code.

But I tested it in chrome and js bin and changed the condition to true, and it could alert "Hi". There was no problem like "most browsers will return the second statement and ignore the condition" mentioned in the book. ,Why is this:

if(true){ function sayHi(){ alert("Hi!"); } } else { function sayHi(){ alert("Yo!"); } } sayHi();// Hi!

Please advise, thank you!

淡淡烟草味
淡淡烟草味

reply all (2)
为情所困

true is a literal, not a variable. The browser will directly optimize your if statement when parsing, similar to this:

if(true){ function sayHi(){ alert("Hi!"); } } else { function sayHi(){ alert("Yo!"); } } 变成 function sayHi(){ alert("Hi!"); }

However, the author is referring to another situation

if(condition){ function sayHi(){ alert("Hi!"); } } else { function sayHi(){ alert("Yo!"); } } var condition = true sayHi()
    三叔

    After the compiler gets this code, it finds that there are two duplicate function declarations in the same scope. The first declaration will be directly replaced by the second declaration.
    js does not recommend declaring functions inside blocks.
    In strict mode, this code reports an error directly.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!