Stanislav Zorjan - Stasha - Full Stack Software Engineer and Game Development Hobbyist - Prague


JavaScript OOP - Classes & Objects
JavaScript OOP - Methods & Properties
JavaScript OOP - Getters & Setters
JavaScript OOP - Encapsulation
JavaScript OOP - Inheritance

 

JavaScript OOP - Encapsulation

 


// Global properties
// They can be accessed from everywhere
// Using accessor modifiers in global scope nas no effect, thus all of them
// will have same value (last asigned one).
someProperty = "Document Property 1";
var someProperty = "Document Property 2";
this.someProperty = "Document Property 3";

// "someProperty == var someProperty == this.someProperty"
// will have same value "Document Property 3"



// Static property
SomeClass.someProperty = "Static Property";

// Inside a class we can use: "Global", "Public", "Private" access modifyers
// They doesn't hide(override) each other if same name is used.
// Inside a local (method) scope, variables with the same name and access modifyer
// will hide those declared in class scope while accessed from within the same local scope
// 
// Class constructor is class body itself
function SomeClass(){
    
    // Global property
    // It is available to all javascript inside or outside the class
    // once object of this class is created.
    // Only one instance can exist in global scope
    // Use this type only when you must.
    globalProperty = "Global Property";
    
    // Public property
    this.someProperty = "Public Property";
    
    // Private property
    var someProperty = "Private Property";
    
    // Global method
    // It is available to all javascript inside or outside the class
    // once object of this class is created.
    // Only one instance(unique) can exist in global scope
    // Use this type only when you must!
    globalFunction = function(){
        return getPrivateProperty();
    }
    
    // Private method
    function getPrivateProperty(){
        return someProperty;
    }
    
    // Public method
    this.getPrivateProperty = function(){
        return getPrivateProperty();
    }
    
    // Public method
    this.getLocalProperty = function(){
        alert(someProperty);
        
        // Local variable
        var someProperty = "Method Property";
        // Because local variable "someProperty" is declared locally
        // (it hides private "someProperty" variable),
        // first alert will display "undefined" 
        // (STRANGE BECAUSE ALERT IS CALLED BEFORE LOCAL DECLARATION), 
        // but if local "someProperty" variable is not declared
        // alert will display "Private Property" value
        
        
        alert(someProperty);
        return someProperty;
    }
}





var gp = new SomeClass();

alert(someProperty+", "+this.someProperty+", "
+SomeClass.someProperty+", "+gp.someProperty+", "
+gp.getPrivateProperty()+", "+gp.getLocalProperty());