Categories:
Partners
Web Hosting
We've partnered with HostGator for reliable, affordable hosting starting at $3.95/mon. Use coupon code "javascriptkit25" for 25% off any package.

Subclasses and Superclasses

In Java and C++, there is an explicit concept of the class hierarchy. i.e. Every class can have a super class from which it inherits properties and methods. Any class can be extended, or sub-classed so the resulting subclass can inherit its parent's behavior. As we have seen, JavaScript supports prototype inheritance instead of class based. It's possible for inheritance to happen other ways, however.

The following is an example of inheritance through functions.

<script language="javascript" type="text/javascript">
<!--

// thanks to webreference

function superClass() {
  this.supertest = superTest; //attach method superTest
}

function subClass() {
  this.inheritFrom = superClass;
  this.inheritFrom();
  this.subtest = subTest; //attach method subTest
}

function superTest() {
  return "superTest";
}
  
function subTest() {
  return "subTest";
}


 var newClass = new subClass();

  alert(newClass.subtest()); // yields "subTest"
  alert(newClass.supertest()); // yields "superTest"
 
//-->
</script>

Prototype based inheritance is a far better bet for JavaScript applications in most cases.

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.