Javascript function scoping and hoisting

后端 未结 18 2930
孤街浪徒
孤街浪徒 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:10

    1. function declaration function a(){} is hoisted first and it behaves like var a = function () {};, hence in local scope a is created.
    2. If you have two variable with same name (one in global another in local), local variable always get precedence over global variable.
    3. When you set a=10, you are setting the local variable a , not the global one.

    Hence, the value of global variable remain same and you get, alerted 1

提交回复
热议问题