Javascript function scoping and hoisting

后端 未结 18 2997
孤街浪徒
孤街浪徒 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 04:56

    Function hoisting means that functions are moved to the top of their scope. That is,

    function b() {  
       a = 10;  
       return;  
       function a() {} 
    } 
    

    will be rewritten by the interpeter to this

    function b() {
      function a() {}
      a = 10;
      return;
    }
    

    Weird, eh?

    Also, in this instance,

    function a() {}
    

    behaved the same as

    var a = function () {};
    

    So, in essence, this is what the code is doing:

    var a = 1;                 //defines "a" in global scope
    function b() {  
       var a = function () {}; //defines "a" in local scope 
       a = 10;                 //overwrites local variable "a"
       return;      
    }       
    b();       
    alert(a);                 //alerts global variable "a"
    
    0 讨论(0)
  • 2020-11-21 04:58

    Its all depends on the scope of variable 'a'. Let me explain by creating scopes as images.

    Here JavaScript will create 3 scopes.

    i) Global scope. ii) Function b() scope. iii) Function a() scope.

    Its clear when you call 'alert' method scope belongs to Global that time, so it will pick value of variable 'a' from Global scope only that is 1.

    0 讨论(0)
  • 2020-11-21 05:01

    function a() { } is a function statement, which creates an a variable local to the b function.
    Variables are created when a function is parsed, regardless of whether the var or function statement gets executed.

    a = 10 sets this local variable.

    0 讨论(0)
  • 2020-11-21 05:07

    scpope & closure & hoisting (var/function)

    1. scpope : the global var can be access in any place(the whole file scope), local var only can be accessed by the local scope(function/block scope)!
      Note: if a local variable not using var keywords in a function, it will become a global variable!
    2. closure : a function inner the other function, which can access local scope(parent function) & global scope, howerver it's vars can't be accessed by others! unless, your return it as return value!
    3. hoisting : move all declare/undeclare vars/function to the scope top, than assign the value or null!
      Note: it just move the declare,not move the value!

    var a = 1;                
    //"a" is global scope
    function b() {  
       var a = function () {}; 
       //"a" is local scope 
       var x = 12; 
       //"x" is local scope 
       a = 10;
       //global variable "a" was overwrited by the local variable "a"  
       console.log("local a =" + a);
       return console.log("local x = " + x);
    }       
    b();
    // local a =10
    // local x = 12
    console.log("global a = " + a);
    // global a = 1
    console.log("can't access local x = \n");
    // can't access local x = 
    console.log(x);
    // ReferenceError: x is not defined

    0 讨论(0)
  • 2020-11-21 05:08

    From my piece of knowledge, hoisting happens with the variable declaration and function declaration, for example:

    a = 7;
    var a;
    console.log(a) 
    

    What happens inside JavaScript's engine:

    var a;
    a = 7;
    console.log(a);
    // 7
    

    Or:

    console.log(square(7)); // Output: 49
    function square(n) { return n * n; }
    

    It will become:

    function square(n) { return n * n; }
    console.log(square(7)); // 49
    

    But assignments such as variable assigment, function expression assignment will not be hoisted: For example:

    console.log(x);
    var x = 7; // undefined
    

    It may become like this:

    var x;
    console.log(x); // undefined
    x = 7;
    
    0 讨论(0)
  • 2020-11-21 05:09

    ES5: function hoisting & variable hoisting

    function hoisting priority is greater than variable hoisting

    "use strict";
    
    /**
     *
     * @author xgqfrms
     * @license MIT
     * @copyright xgqfrms
     * @created 2016-06-01
     * @modified
     *
     * @description function-hoisting.js
     * @augments
     * @example
     * @link
     *
     */
    
    (function() {
      const log = console.log;
    
      var a = 1;
      function b() {
        a = 10;
        log(`local a`, a)
        return;
        // function hoisting priority is greater than variable hoisting
        function a() {}
      }
      b();
      log(`global a`, a);
      // local a 10
      // global a 1
    })();
    
    
    
    

    which is equal to

    (function() {
      const log = console.log;
    
      // define "a" in global scope
      var a = 1;
      function b() {
        // define "a" in local scope
        var a ;
        // assign function to a
        a = function () {};
        // overwrites local variable "a"
        a = 10;
        log(`local a`, a);
        return;
      }
    
      b();
      // log global variable "a"
      log(`global a`, a);
    
      // local a 10
      // global a 1
    })();
    
    

    the reason behind of hoisting

    var a = 1;                
    //"a" is global scope
    function b() {  
       var a = function () {}; 
       //"a" is local scope 
       var x = 12; 
       //"x" is local scope 
       a = 10;
       //global variable "a" was overwrited by the local variable "a"  
       console.log("local a =" + a);
       return console.log("local x = " + x);
    }       
    b();
    // local a =10
    // local x = 12
    console.log("global a = " + a);
    // global a = 1
    console.log("can't access local x = \n");
    // can't access local x = 
    console.log(x);
    // ReferenceError: x is not defined
    
    /**
     *  scpope & closure & hoisting (var/function)
     *  
     * 1. scpope : the global var can be access in any place(the whole file scope), local var only can be accessed by the local scope(function/block scope)!
     * Note: if a local variable not using var keywords in a function, it will become a global variable!
     * 
     * 2. closure : a function inner the other function, which can access local scope(parent function) & global scope, howerver it's vars can't be accessed by others! unless, your return it as return value!
     * 
     * 3. hoisting : move all declare/undeclare vars/function to the scope top, than assign the value or null!
     * Note: it just move the declare, not move the value!
     * 
     */
    
    

    ES6 let, const no exist hoisting

    (() => {
      const log = console.log;
      log(a)
      // Error: Uncaught ReferenceError: Cannot access 'a' before initialization
      let a = 1;
    })();
    
    
    
    
    (() => {
      const log = console.log;
      log(b)
      // Error: Uncaught ReferenceError: Cannot access 'b' before initialization
      const b = 1;
    })();
    
    

    refs

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

    0 讨论(0)
提交回复
热议问题