2

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?

1

1 Answer 1

4

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Great, that did the job, also thanks for the apply for all arguments!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.