JS is OO

To accompany a slide about inheritance, polymorphism, abstraction, and encapsulation in Javascript.

by psyon001

JavaScript

(function (){
    /* Declare all vars */
    var Employee, FED, Designer, Person, Jim, Tim;
    
    /* A way to make prototype/constructor setup more concise. */
    if (typeof Object.create !== 'function') {
        Object.create = function (o) {
            function F() {}
            F.prototype = o;
            return new F();
        };
    }
    
    /* Abstract Object cannot be instantiated, but can be inherited */
    Person = {
        name:'anonymous',
        setName: function (name){
            this.name = name;
            return this;
        },
        getName: function (){
            return this.name;
        }
    };
    /* Won't work. */
    // var me = new Person();
    
    /* Define a base Employee class. */
    Employee = function (job){
        var strJob = job || "unemployed";
        /**
         *  Get this employee's job
         *  @returns {String} Job
         */
        this.getJob = function (){
            return strJob;
        };
        this.setJob = function (job){
            strJob = job;
            return this;
        };
    };
    /* Prototype inheritance */
    Employee.prototype = Person;
    
    FED = new Employee("does magic"); // A FED is an employee who is a person, no matter what your boss thinks.
    Designer = new Employee("ensures blueness"); // Designers are people, but just barely. :)
    
    /* Chainability is achieved by always returning this */
    Jim = Object.create(FED).setName("Jim"); // Jim is a FED 
    /* Javascript is faster manipulating properties directly. */
    Tim = Object.create(Designer); // Tim is a Designer 
    Tim.name = "Tim";
    
    //Designer.setJob("ensure blueness");
    
    /* What is your job? */
    /* We can access public properties directly. Also there are true private variables. */
    document.write(Jim.name + " " + Jim.getJob() + "<br />");
    /* You can still define a public getter/setter method. */
    document.write(Tim.getName() + " " + Tim.getJob() + "<br...