2 Replies - 1463 Views - Last Post: 03 May 2012 - 05:55 PM

#1 psykoprogrammer  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 2
  • View blog
  • Posts: 72
  • Joined: 09-October 06

Javascript Inheritance

Posted 04 December 2006 - 04:50 AM

Description: A small example demonstrating inheritance in Javascript, complete with calling base class constructors and methods.
//--------------------------------------------
// IEmployee Class - Basic employee class
//--------------------------------------------
function IEmployee(name, department)
{
  this.IEmployee = this;

  this.name = name;
  this.department = department;

  this.work = function()
  {
    alert(this.name + ' is working for 8 hours in the ' + this.department + ' department.');
  }
}

//-----------------------------------------------
// IManager - Class inherits from IEmployee
//-----------------------------------------------
function IManager(name, department)
{
  this.IManager = this;

  // Call the base constructor.
  IEmployee.call(this, name, department);

  this.work = function()
  {
    alert(this.name + ' is telling peeps what to do for 6 hours in the ' + this.department + ' department.');
  }
}
IManager.prototype = new IEmployee;

//--------------------------------------------------
// ISalesPerson - Class inherits from IEmployee
//--------------------------------------------------
function ISalesPerson(name, department, quota)
{
  this.ISalesPerson = this;
  this.expectedQuota = quota;
  this.currentQuota = 0;

  IEmployee.call(this, name, department);

  this.sell = function(dollarAmount)
  {
    if (this.currentQuota < this.expectedQuota) this.currentQuota += dollarAmount;
    this.IEmployee.work();
    alert('Quota: ' + this.currentQuota + ' of ' + this.expectedQuota);
  }
}
ISalesPerson.prototype = new IEmployee;

//------------------------------------------------------------
// Instantiate each class, demonstrating how they work
//------------------------------------------------------------
adam = new IEmployee('Adam', 'Engineering');
adam.work();

bob = new IManager('Bob', 'VP of Development');
bob.work();

john = new ISalesPerson('John', 'Corporate Sales', 5000);
john.sell(1000);



Is This A Good Question/Topic? 0
  • +

Replies To: Javascript Inheritance

#2 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 4138
  • View blog
  • Posts: 13,074
  • Joined: 08-June 10

Re: Javascript Inheritance

Posted 08 June 2010 - 07:39 PM

If you want to test, whether a certain object belongs to a specific "class", donít forget to reset the .constructor property to the original function after invoking the inheritance.
Was This Post Helpful? 0
  • +
  • -

#3 frefrefre  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 0
  • Joined: 03-May 12

Re: Javascript Inheritance

Posted 03 May 2012 - 05:55 PM

good job
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1