Javascript function scoping and hoisting

后端 未结 18 3001
孤街浪徒
孤街浪徒 2020-11-21 04:20

I just read a great article about JavaScript Scoping and Hoisting by Ben Cherry in which he gives the following example:

var a = 1;

function b() {
    a =          


        
18条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 05:23

    What you have to remember is that it parses the whole function and resolves all the variables declarations before executing it. So....

    function a() {} 
    

    really becomes

    var a = function () {}
    

    var a forces it into a local scope, and variable scope is through the entire function, so the global a variable is still 1 because you have declared a into a local scope by making it a function.

提交回复
热议问题