Andrius Naruševičius
Andrius Naruševičius

Reputation: 8578

Javascript inheritance of constructor with variables

Let's say I have

function Point(x, y)
{
    this.X = x;
    this.Y = y;
}

and I want to have a class Point2. Using this and this I came up with this code:

function Point2(x, y)
{
    this.X = x; // <-
    this.Y = y; // <-
}

Point2.prototype = new Point();
Point2.prototype.constructor = Point;

However, if I have many variables or many inheritances, I don't want to repeat the assignment of properties all the time (see the lines with <-. If I write it like this, like it says in the second link:

Point2.call(this);

, I get an error: Maximum call stack size exceeded, because it calls itself, which looked suspicious for me from the start.

So, is there a way to call the parent constructor with the same incoming values instead of repeating the whole code?

Upvotes: 2

Views: 65

Answers (1)

SLaks
SLaks

Reputation: 887305

You need to call the parent constructor, not your own constructor:

Point.call(this, x, y);

If the arguments are always the same, you can also write Point.apply(this, arguments);

Upvotes: 4

Related Questions