Javascript Class Extensions Example

Basic examples of extending classes in prototypical fashion

by Riffic

JavaScript

function Animal( conf ){
    var defaults = {
        type: '',
        age: 0
    }
    this.fields = angular.extend( defaults, conf );
}
//Exention of class with same methods, different implementation, typical implementation
var Cat = (function(){
    function Cat( conf ){
        conf.type = "cat";
        Animal.apply( this, conf );
        var defaults = {
            catType: "tabby",
        };
        this.fields = angular.extend( this.fields, defaults, conf );
    }   
    Cat.prototype = new Animal();
    Cat.prototype.makeNoise = function(){
        console.log("MEOW..");
    }
    return Cat;
})();

var Dog = (function(){
    function Dog( conf ){
        conf.type = "dog";
        Animal.apply( this, conf );
        var defaults = {
            dogType: "lab",
        };
        this.fields = angular.extend( this.fields, defaults, conf );
    }   
    Dog.prototype = new Animal();
    Dog.prototype.makeNoise = function(){
        console.log("BARK...");
    }
    return Dog;
})();

newCat = new Cat( {catType: "siamese"} );
newDog = new Dog( {dogType: "poodle"} );
console.log( newCat, newDog );
//debugger;


function Vehicle( conf ){
    var defaults = {
        type: '',
        color: 'red'
    }
    this.fields = angular.extend( defaults, conf );
}
//Exention of class with same methods, different implementation, based on constructor, not instanceof Vehicle
var Car = (function(){
    function Car( conf ){
        conf.type = "car";
        Vehicle.apply( this, conf );
        var defaults = {
            carType: "sedan",
        };
        this.fields = angular.extend( this.fields, defaults, conf );
    }   
    Car.prototype = {
        constructor: Vehicle,
        getTireSize: function(){
            console.log("small tire size");
        }
    }    
    return Car;
})();

var Truck = (function(){
    function Truck( conf ){
        conf.type = "truck";
        Vehicle.apply( this, conf );
        var defaults = {
            truckType: "4x4",
...