6.27.2015

Javascript scope

Defining variables and functions:
var glob = 'glob'; // global variable
function printGlob() { // global function
    console.log(glob);
}
function Person(name, nat, gend) { // constructor
    this.name = name; // public variable
    nationality = nat; // global variable ("no var" will look up the scope chain   until it finds the variable or hits the global scope (at which point it will create it))
    var gender = gend; // local variable
    var privateMethod = function() {
        console.log(executing private method);
    }
    this.getName = function () { // privileged method that can access to private   method and local variable
        console.log(gender);
        privateMethod();
        return this.name;
    }

}
// public method (same as getName, but more memory efficient since all instances   share the same method)
Person.prototype.getName2 = function () { 
// can not access to private method and local variable
console.log(this.name);
    return this.name;
};
// static property
Person.town = "South Park";
How to use variables and functions:
// Access to global variable
nationality; // undefined since we haven't initialized it
// Create a new instance
var woody = new Person('Woody', 'TW', 'M');
// Access to global variable
nationality; // TW
// Access private property
woody.gender; // undefined
// Access privileged method
woody.getName();
// Access public property
woody.name; // Woody
// Access privileged method
woody.printPrivate(); 
// Access public method
woody.getName2(); 
// Access static property on an instance
woody.town; // undefined
// Access static property on the constructor object
Person.town; // "South Park"