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 - Inheritance

 

// Template Class
function SomeClass(){
    
    this.firstName = "";
    
    this.setFirsName = function(value){
        this.firstName = value;
    }
    
    this.getFirstName = function(){
        return this.firstName;
    }
}

// Extending SomeClass
// By using a class.prototype we are "injecting" object that will act as 
// the prototype for every new created or existing instance.
ExtendedSomeClass.prototype = new SomeClass();
// Because constructor in javascript is body of the class itself, we asign
// class to class.prototype.constructor.
// If we don't asign constructor to prototype.constructor, "SomeClass" 
// will be called as a constructor;
ExtendedSomeClass.prototype.constructor = ExtendedSomeClass;


//Class that extends SomeClass
function ExtendedSomeClass(){
    
    // Public method
    this.methodFromExtendedSomeClass = function(){
        return "Method from ExtendedSomeClass"
    }
    
    // Storing super method for later use. 
    var firstName = this.getFirstName;
    
    // Overriding getFirstName from super class.
    // If we override super method, the reference to it is lost
    // so if we need to access super method, we have to store it 
    // in some variable, as we did in previous line of code.
    this.getFirstName = function(){
        return this.firstName;
    }
}

// Creating "SomeClass" object
var sc = new SomeClass();
// Setting first name
sc.setFirsName("First Name");

// Creating "ExtendedSomeClass" object
var esc = new ExtendedSomeClass();
// Setting first name in extended class
esc.setFirsName("Extended First Name")

alert(sc.getFirstName()+", "+esc.getFirstName()+", "
+esc.methodFromExtendedSomeClass()+", "+(esc instanceof SomeClass));