Object-Oriented Programming with JavaScript, Part II: Methods: Protecting Private Data - Doc JavaScript | WebReference

Object-Oriented Programming with JavaScript, Part II: Methods: Protecting Private Data - Doc JavaScript


Object-Oriented Programming with JavaScript, Part II: Methods

Protecting Private Data

We saw on the previous page that private data members are not protected. Each subclass can change them 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.

Next: A Final Word


Produced by Yehuda Shiran and Tomer Shiran
All Rights Reserved. Legal Notices.
Created: March 26, 2001
Revised: March 26, 2001

URL: http://www.webreference.com/js/column80/9.html