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!')
}
}
黄舟2017-07-05 10:40:34
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
黄舟2017-07-05 10:40:34
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
伊谢尔伦2017-07-05 10:40:34
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
PHP中文网2017-07-05 10:40:34
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,