spacer
Yehuda Shiran February 14, 2001
Defining Duplicate Functions
Tips: February 2001

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
News Flash: Adobe Has iPhone Workaround
Adobe's Flash 10.1 Goes Mobile (Minus iPhone)
A Salute to Visionary CEOs

Sometimes you want to define a method in a superclass and then override it with a method in a subclass. For overriding to work correctly, both methods need to have the same name. But how do you define two distinct functions with the same name? If you define them as global variables, the last definition overrides the first one. The solution is to define each function inside its relevant class. When you do that, each function is associated with the right class, and there is no overriding of function definitions. Still, the subclass definition overrides the superclass one. The following code demonstrates this behavior. The class subClass() defines the method allBye() which prints an alert box that greets you from subClass(). The class superClass() defines the method allBye() as well, greeting you from superClass(). The subclass method overrides (by design) the superclass method. When clicking here, you'll get two alert boxes. The first one, alert(newClass.bye()), demonstrates that the definition of the allBye() method in subClass() was not overridden by the later definition inside superClass(). The second alert box, alert(newClass.hello()), demonstrates the inheritance of the hello() method by subClass(). here are the classes:

function subClass() {
  this.inheritFrom = superClass;
  this.inheritFrom();
  this.bye = allBye;
  
  function allBye() {
	return "Bye from subClass";
  }
}

function superClass() {

  this.bye = allBye;
  this.hello = superHello;
  
  function superHello() {
    return "Hello from superClass";
  }
  
  function allBye() {
	return "Bye from superClass";
  }
  
}
var newClass = new subClass();

And the print function is:

function printMethod() {
  alert(newClass.bye());
  alert(newClass.hello());
}


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Building a Banking Application Home Page with OOP · Mixing Scripting Languages · Review: phpFox, a Social Networking CMS with all the Bells and Whistles
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Enterprise 2.0: Social Networking in the Cloud · BroadSoft Marketplace Hastens Pace of Telephony Innovation · Review: HTC Hero for Sprint