Global and Local and Private Functions (Javascript)

前端 未结 6 642
情深已故
情深已故 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:00

    What is the difference between local and private variables? Is there one?

    Depends in which context they are used. Generally they mean the same thing. From the OOP perspective, a local variables is usually called private.

    How does one make a variable global or local, They said something about putting 'var =' before it, but it was very vague.

    When you put var before variable, it becomes local variables, in the absence though, it becomes global variable. For example:

    var foo = 1; // local
    foo = 1; // global equivalent to window.foo = 1 becomes part of window object
    

    More Practical Example:

    function myfunc(){
      var foo = 1; // presence of var keyword
      bar = 2;     // absence of var keyword
    }
    
    alert(foo); // error eg undefined
    alert(bar); // 2 because bar is part of window global object
    

提交回复
热议问题