billywhizz
6/1/2014 - 1:55 PM

javascipt.inheritance.js

function inherits(ctor, superCtor) {
  ctor.super_ = superCtor;
  ctor.prototype = Object.create(superCtor.prototype, {
    constructor: {
      value: ctor,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
};

function Service() {
  console.log("Service class initialised");
}
Service.prototype.getChildById = function(searchId, collection){
  console.log("Service.getChildById called");
};
Service.prototype.buildCriteria = function(accountId, criteria) {
  console.log("Service.buildCriteria called");
};
Service.prototype.getAll = function(accountId, options, callback) {
  console.log("Service.getAll called");
};

// A subclass of Service that inherits all it's methods
function ShipmentService() {
  // ensure we return a new Object instance if we are called as a function
  if (!(this instanceof ShipmentService)) {
    return new ShipmentService();
  }
  Service.call(this);
  console.log("ShipmentService class initialised");
}
// we must do this before we add any prototype methods to the subclass
inherits(ShipmentService, Service);
ShipmentService.prototype.getShipmentCouriers = function(accountId, shipmentId, callback) {
  console.log("ShipmentService.getShipmentCouriers called");
};
ShipmentService.prototype.getShipmentCustomsInfo = function(accountId, shipmentId, callback) {
  console.log("ShipmentService.getShipmentCustomsInfo called");
};
ShipmentService.prototype.volumesByMonth = function(accountId, month, year, callback) {
  console.log("ShipmentService.volumesByMonth called");
};

// A subclass of ShipmentService that inherits all methods of ShipmentService and Service
function SpecialShipmentService() {
  // ensure we return a new Object instance if we are called as a function
  if (!(this instanceof SpecialShipmentService)) {
    return new SpecialShipmentService();
  }
  ShipmentService.call(this);
  console.log("SpecialShipmentService class initialised");
}
// we must do this before we add any prototype methods to the subclass
inherits(SpecialShipmentService, ShipmentService);
SpecialShipmentService.prototype.specialShipmentMethod = function(accountId, shipmentId, callback) {
  console.log("SpecialShipmentService.specialShipmentMethod called");
};
SpecialShipmentService.prototype.volumesByMonth = function(accountId, month, year, callback) {
  console.log("SpecialShipmentService.volumesByMonth called");
  // i also want to call the parent classes default method here
  ShipmentService.prototype.volumesByMonth.call(this);
};

var Model = {
  Service: Service,
  ShipmentService: ShipmentService,
  SpecialShipmentService: SpecialShipmentService
};

var repl = require("repl").start("> ");
repl.context.Model = Model;