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

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

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().


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, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business