inheritance JS

by Himanshu Joshi

HTML

<!--
3 step process 
1. call the parent constructor function
2. create a prototype.
3. return constructor type of subclass to its type.-->

JavaScript

var Model = function () {
    this.names = ["name1", "name2"];
};

var Item = function () {
    //When inheriting in Javascript you must 
    //call the inherited function's constructor manually.
    Model.call(this);
};

//Inherit Model's prototype so you get all of Model's methods.
Item.prototype = Object.create(Model.prototype);
Item.prototype.constructor = Item;

Item.prototype.init = function (item_name) {
    this.names[0] = item_name;
};

var Employee = function () {
    Model.call(this);
};

Employee.prototype = Object.create(Model.prototype);
Employee.prototype.constructor = Employee;

var myItem = new Item();
myItem.init("New Name");
//prints New Name, name2
console.log(myItem.names);


var myEmployee = new Employee();
//prints name1, name2
console.log(myEmployee.names);