javascript - I see a function in the function declaration section and I don't quite understand it.
我想大声告诉你
我想大声告诉你 2017-07-05 10:38:34
0
4
774

This is an example of js elevation
See that the function declaration has a code

if(condition){
    function sayHi(){
        alert('hi')
    }
}else{
    function sayHi(){
        alert('Yo')
    }
}

It is said that this code has invalid syntax. Most browsers will return the second statement, and Firefox will return the first statement. Why is this?
If it is changed to function expression form, why is this?

var sayHi;
if(condition){
    sayHi=function(){
        alert('Hi')
    }
}else{
    sayHi=function(){
        alert('Yo!')
    }
}
我想大声告诉你
我想大声告诉你

reply all(4)
黄舟

Because the first one is a function declaration, but functions are generally not declared in if-else

The second one is to assign the anonymous function to the variable. There is no such thing as promotion

黄舟

Writing function xxx(){} directly will result in early declaration. If there are two such functions with the same name, it is equivalent to executing var xxx twice at the top, so it is invalid

伊谢尔伦

It has nothing to do with declaration prefix. At that time, the JavaScript specifications were still ES5, browsers had not yet implemented block-level scope (ES2016+), and the scope level was only the function level. So you wrote it

if(condition){
    function sayHi(){
        alert('hi')
    }
}else{
    function sayHi(){
        alert('Yo')
    }
}

and written by

function sayHi(){
  alert('hi')
}
function sayHi(){
  alert('Yo')
}

No essential difference

洪涛

js is declared in advance! ! ! The function will be directly mentioned at the top of the scope when it is declared. There is no scope in if, so the two functions are one scope, and the second one will replace the first one. ! As for your second code, you declare the variable sayhi first, and then assign the value to sayhi after the if judgment,

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template