Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call constructor within another constructor

Tags:

javascript

I found the following example in Dojo: The Definitive Guide:

function Shape(centerX, centerY, color)
{
  this.centerX = centerX;
  this.centerY = centerY;
  this.color = color;
};

function Circle(centerX, centerY, color, radius)
{

  this.base = Shape;
  this.base(centerX, centerY, color);
  this.radius = radius;
};

c = new Circle(10, 20, "blue", 2);

Please explain how this example works. I understand that when we call the constructor Circle, then this refers to the object being created, so it is clear for me why c object has base and radius properties, but how does it get centerX, centerY, color?

like image 422
drnextgis Avatar asked Jun 30 '26 22:06

drnextgis


2 Answers

Because you've assigned the Shape function to this, and then invoked it by doing this.base().

So here, the base method is the Shape function, and when you do obj.method(), the value of this in method is set to the obj. Therefore the value of this in Shape is your new Circle object.


A more common approach is to use .call() instead of setting the function onto the object.

Shape.call(this, centerX, centerY, color);

This invokes the Shape function with its this value set to whatever you provided as the first argument. The rest of the arguments passed to .call() are just passed on as regular arguments to Shape.


I would guess they used this.base = Shape because there's some other use for this.base elsewhere in the code.

your Circle gets a new base property which resolves to the function named Shape:

this.base = Shape;

Then, that function is invoked and passed the centerX, centerY, and color parameters. Since your this object never changes, centerX and friends are assigned to the same object which later gets the radius property:

this.base(centerX, centerY, color);
this.radius = radius;
like image 21
Dan O Avatar answered Jul 02 '26 12:07

Dan O



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!