February 14, 2001 - Defining Duplicate Functions | WebReference

February 14, 2001 - Defining Duplicate Functions

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

Yehuda Shiran, Ph.D.
Doc JavaScript

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());
}