Global and Local and Private Functions (Javascript

2019-02-22 03:37发布

问题:

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.

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

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

回答1:

  1. None, People use "private" because they are mistaken and are meant to say "local"

  2. local variables are defined as

var foo = "local";

global variables are a properties of the global scope object (which is window in the browser)

window.foo = "global";

The fact you can do foo = "global"; without first assigning variable foo with var foo is a "bug". This is fixed in ES5 strict mode.

(function () { "use strict"; foo = 42; })()

gives ReferenceError: foo is not defined

Note that you can make variables global by declaring them in outer most scope

var foo = "global";
function bar() {
  var foo = "local";
}

It should be noted that you shouldn't have any code in outer most scope, ever. You should be wrapping all your scope in anonymous functions so that you get "module level scope". This means you have a per file based top level scope. This is part of the module pattern.



回答2:

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


回答3:

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


回答4:

Javascript has a function scope, any variable defined within a function with a var keyword is local to the function and is not visible outside. variables defined in function without var keyword are globals and are visible everywhere.

function test(){
  var local = 'local'; // this is local
  global = 'global'; // this is global
}

test(); // call a function

alert(local) // undefined
alert(global) // global


回答5:

Private variables only make sense when you are constructing objects. The typical prototype pattern has you add any necessary variables and helper functions as properties of the instance of the object and/or its prototype, but this has the disadvantage of making them visible to anyone with access to the object. To avoid this, there is an alternative pattern where the variables are local variables of the constructor, and all the methods are declared in the constructor scope and only the public ones are assigned as actual properties of the object.



回答6:

I find all your answers very odd as I thought it was as follow :

    /* A globally scoped and public variable */
    var globalVariable = 'global';
    /* A globally scoped and public constructor */
    function Obj() {
        /* private */
        /* A locally scoped and private variable */
        var privateVariable = 'private';
        /* A locally scoped and private method */
        privateMethod = function() {
            return privateVariable;
        }
        /* public */
        /* A locally scoped and public variable */
        this.publicVariable = 'public';
        /* A locally scoped and public method */
        this.publicMethod = function() {
            console.log(privateVariable + ' ' +
                privateMethod() + ' ' +
                globalVariable + ' ' +
                this.publicVariable);
        }
    };
    /* A globally scoped and public object */
    var obj = new Obj();
    /* displaying various variables and calling methods */
    console.log(globalVariable); // global
    console.log(obj.privateVariable); // undefined
    /* if uncommented will display : ReferenceError: privateVariable is not defined */
    // console.log(privateVariable);
    /* if uncommented will display : TypeError: obj.privateMethod is not a function */
    // obj.privateMethod();
    privateMethod(); // nothing is displayed
    console.log(obj.publicVariable); // public
    obj.publicMethod(); // private private global public