JS Inheritance

by Sukanya Halder

HTML

<!-- Notes : JS Inheritance
the call method to modify the this object; the this object is the Car object, so the call to the parent constructor function creates year, make, and model on the Car object. The Function object has another method, apply, that does the same thing, but the extra parameters are passed as an array instead of as a comma-delimited list.

The inheritance is accomplished by changing the Car prototype object to be a new Vehicle object. 
Remember that the prototype is the object that is cloned to create the new object. 
By default, the prototype is of type Object. 
After the new Vehicle is assigned to the prototype, the constructor of that Vehicle is changed to be the Car constructor.
 Car.prototype = new Vehicle();
    Car.prototype.constructor= Car;

you must use the call method and pass the this object
-->

JavaScript

var car;
var Vehicle = (function () {
    function Vehicle(year, modelname) {
        //console.log(this);
        var model = modelname;
        var modelmakeyear = year;
        this.makemodel = function () {
            return model;
        };
        this.makeyear = function () {
            return modelmakeyear;
        };
    }
    Vehicle.prototype.show = function () {
        console.log(this.makemodel() + "--" + this.makeyear());
    };
    return Vehicle;
})();

var Car =(function(mainVehicle){
    
    function Car(makemodel,year){
        mainVehicle.call(this,year,makemodel);        
    }
    Car.prototype = new Vehicle();
    Car.prototype.show=function(){console.log(this.makemodel()+"-Sedan @ "+this.makeyear());};// polymorphism
    Car.prototype.constructor= Car;
    Car.prototype.cartype=function(){console.log("Sedan")};
    return Car;
})(Vehicle);
//console.log(Car);

car = new Vehicle("BMW", "2015");
car2 = new Vehicle("Mercedes", "2015");
car.show();
car2.show();
var accord = new Car("Honda Accord","2015");
accord.show();
accord.cartype();