March 29, 2001 - Protecting Private Data Elements
![]() |
March 29, 2001 Protecting Private Data Elements Tips: March 2001
Yehuda Shiran, Ph.D.
|
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);


Find a programming school near you