February 16, 2001 - Avoiding Function Nesting | WebReference

February 16, 2001 - Avoiding Function Nesting

Yehuda Shiran February 16, 2001
Avoiding Function Nesting
Tips: February 2001

Yehuda Shiran, Ph.D.
Doc JavaScript

Sometimes, you need to define a function inside another function. This is a good way to protect functions against overriding. If you inadvertently define a function twice at the top level of the script hierarchy, the last definition will hold. But, when dealing with two classes, you may want to define two different functions with the same name. You can protect both versions by nesting each function inside its class definition. Here is an example for nested definitions, not necessarily of the same functions:

function superClass() {
  this.bye = superBye;
  this.hello = superHello;
  
  function superHello() {
    return "Hello from superClass";
  }
  
  function superBye() {
    return "Bye from superClass";
  }
}
function subClass() {
  this.inheritFrom = superClass;
  this.inheritFrom();
  this.bye = subBye;
  
  function subBye() {
	return "Bye from subClass";
  }
}

The problem is that Netscape 4.04 on Mac does not like the bottom nesting. It is much happier when the function subBye() is defined at the top level of the script hierarchy, like this:

function superClass() {
  this.bye = superBye;
  this.hello = superHello;
  
  function superHello() {
    return "Hello from superClass";
  }
  
  function superBye() {
    return "Bye from superClass";
  }
}
function subClass() {
  this.inheritFrom = superClass;
  this.inheritFrom();
  this.bye = subBye;
  
  
}
function subBye() {
  return "Bye from subClass";
}

Click here to invoke the following script that activates these objects:

var newClass = new subClass();
function printSub() {
  alert(newClass.bye());
  alert(newClass.hello());
}

So, if Netscape 4.04 on Mac is important for you, it is better not to nest function defintions. When you cannot nest functions, limit yourself to unique functions all over. Use the method assignment syntax to use different functions, as shown above. We defined, for example, superClass' bye() method as superBye(), and subClass' bye() method as subBye().