March 29, 2001 - Protecting Private Data Elements

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

Yehuda Shiran, Ph.D.
Doc JavaScript

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