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

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Google Chrome Playing Catch-Up on Extensions
Open Solutions Alliance Gets New Leadership
Red Hat Spacewalk Expands Linux Management
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.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info

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

webref The latest from WebReference.com Browse >
Popular JavaScript Framework Libraries: An Overview - Part 3 · Accessing Your MySQL Database from the Web with PHP · Working with the DOM Stylesheets Collection
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
MS Access and MySQL · Cisco AutoQoS: VoIP QoS for Mere Mortals · While VoIP Adoption Explodes in Enterprise, Carrier Spending Lags