javascript - The impact of if statements on function declarations
滿天的星座
滿天的星座 2017-06-12 09:27:40
0
3
700
console.log(e());//error

if(true){
    function e() {
        return 10;
    }
}
if(true){

    function e() {
        return 10;
    }
}
console.log(e());//10

If the function declaration promotion is only promoted to the if scope, then what is the reason for the above? (Chrome58 test) Why can the function in the scope of if be accessed from the outside? Please give me the answer

滿天的星座
滿天的星座

reply all(3)
伊谢尔伦

This is actually a historical issue...

Previously in ES5, the specification stipulated that functions could only be declared in the top-level scope and function scope, and not in the block-level scope. Therefore, statements like this are actually illegal:

if (true) {
    function f() {}
}

But in fact, all major browsers do not comply with this specification due to compatibility considerations.

In the current ES6 era, the specification stipulates the existence of block-level scope, and functions can be defined in block-level scope.
But in fact, things are not that simple, because in this case, the defined behavior of the function will be incompatible with the past. In order to ensure compatibility with the past, ES6 stipulates in Appendix B that the browser implementation does not need to comply with the above regulations. Have your own way of behaving.


In ES6 browsers, they actually behave like this:

  1. Allow functions to be defined in block scope

  2. The function declaration will actually be similar to the function expression declared using var, and the function name will be promoted to the top of the current function scope

  3. At the same time, function declarations will also maintain the hoisting behavior in the block-level scope

For your first code, if you take a closer look at what error it reports, you will find that the error is like this: Uncaught TypeError: e is not a function.
This error means that e is not a function. In other words, the variable e exists, but it is not a function. Combining the three rules we mentioned above, it is easy to think that it actually runs like this:

console.log(e());//error

if(true){
    var e = function() {
        return 10;
    }
}

After variable promotion, it will become like this:

var e;
console.log(e());

if(true){
    e = function() {
        return 10;
    }
}

There is no need to mention the second piece of code.

滿天的星座

The function declaration within the if statement will not be promoted, just like the function expression, so the first one is a syntax error, and the second one will output 10

学霸

if(true){
    function e() {
        return 10;
    }
}

Equivalent to =>

var e
//e为undefined 所以下面报错
console.log(e());//error
if(true) {
    e = function() {
        return 10;
    }
    //if内的其他语句
}
//e已经被修改为function了,所以下面的语句正常
console.log(e());//10
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template