Javascript function scoping and hoisting

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

    The function a is hoisted inside function b:

    var a = 1; 
    function b() { 
       function a() {} 
       a = 10; 
       return;
    } 
    b(); 
    alert(a);
    

    which is almost like using var:

    var a = 1; 
    function b() { 
       var a = function () {};
       a = 10; 
       return;
    } 
    b(); 
    alert(a);
    

    The function is declared locally, and setting a only happens in the local scope, not the global var.

提交回复
热议问题