spacer
Yehuda Shiran March 29, 2001
Protecting Private Data Elements
Tips: March 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

Each subclass can change private data types permanently, affecting the values seen by all other subclasses. One way to overcome this problem is to call the superclass constructor from within each subclass constructor. In this way, each subclass creates a local copy of the private data members, and does not step over its peer subclasses memory.

There are two ways to call a constructor from within a constructor. One way is to use the call() method of the superclass constructor. Here is the superclass Shape() and the subclass SquareB():

function Shape() {
  var area = 50;
  this.setArea = function(a) {area = a;};
  this.getArea = function() {return area;};
}

function SquareB() {
  Shape.call(this);
}

After we define shape1B and shape2B, and set shpae1B's area to 100, shape2B's area is not affected (stays at 50). Here is the code:

var shape1B = new SquareB();
var shape2B = new SquareB();

shape1B.setArea(100);

Try it. The second way to call a constructor from within a constructor is by defining the superclass constructor as a method of the subclass constructor. Here is the superclass Shape() and the subclass SquareA():

function Shape() {
  var area = 50;
  this.setArea = function(a) {area = a;};
  this.getArea = function() {return area;};
}

function SquareA() {
  this.Shape = Shape;
  this.Shape();
}

After we define shape1A and shape2A, and set shape1A's area to 100, shape2A's area is not affected (stays at 50). Here is the code:

var shape1A = new SquareA();
var shape2A = new SquareA();

shape1A.setArea(100);

Try it


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