Global and Local and Private Functions (Javascript)

前端 未结 6 632
情深已故
情深已故 2021-01-18 06:46

I am currently reading a book on Javascript by Pragmatic, and I\'m confused about one thing. They have a section on how to make variables global, local, or private.

6条回答
  •  死守一世寂寞
    2021-01-18 07:09

    In the context of the browser, the var keyword scopes the variable to that of the current function.

    var a = 10;
    
    var b = function(a) {
       console.log(a);  # 15
    }
    
    b(15);
    console.log(a);  # 10
    

    If you do not include the var keyword, it is assigned the scope of window and is considered global. Unless you have a very good reason to exclude it, always include the var keyword.

    A variable is considered private if it only exists inside a function scope. This commonly takes the form of an anonymous function. This is not actually a private variable in the common sense of the term, it is simply a local variable.

    (function() {
      var x = 10;
    })();
    
    console.log(x); #undefined
    

提交回复
热议问题