spacer
Yehuda Shiran March 29, 2001
Protecting Private Data Elements
Tips: March 2001

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
OpenOffice 3.2 Lands Amid Critical Changes
Red Hat, IBM Firmly in KVM Virtualization Camp
Red Hat Talks Up Open Source Cloud Plans

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:


The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers

webref The latest from WebReference.com Browse >
Are Google's Language Translation Web Services Ready for Prime Time? · Installing and Using Meeplace, the Business Review CMS · Sending an HTML and Plain Text E-newsletter with ASP.NET, Part 2
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
ANSI SQL Hierarchical Data Processing Basics · Top 10 Threats to Wireless Security · Nuvio Intros NuvioFlex Virtual PBX