traincj
traincj

Reputation: 13

Inheritance of properties through passing constructor parameters

In the following lines of code, adapted from the solutions for the Mozilla JavaScript tutorial, the Ball class inherits the x, y properties from the Shape class.

The Mozilla page seems to imply that to inherit x, y from Shape, they must be defined in the argument list for the Ball constructor (and used in the Shape.call function call). But why is this necessary? The original Shape constructor doesn't take any of these arguments.

Suppose that random is a function defined elsewhere.

var width = canvas.width = window.innerWidth;
var height = canvas.height = window.innerHeight;

function Shape() {
  this.x = random(0,width);
  this.y = random(0,height);
}

function Ball(x, y) {
  Shape.call(this, x, y);
  this.size = random(10,20);
}

Ball.prototype = Object.create(Shape.prototype);
Ball.prototype.constructor = Ball;

This is a note they made on a previous example:

"In this case we specify the inherited properties when we create a new object instance, but note that you'll need to specify them as parameters in the constructor even if the instance doesn't require them to be specified as parameters (Maybe you've got a property that's set to a random value when the object is created, for example.)"

Upvotes: 1

Views: 69

Answers (2)

Christopher Mills
Christopher Mills

Reputation: 26

I'm the person who wrote these docs originally. I must start off by giving a big apology for the confusion caused - my brain was out to lunch that day ;-/

I have updated the code and examples to fix the issues, as documented in this GitHub issue:

https://github.com/mdn/learning-area/issues/7

Please let me know if you notice any more problems with MDN content.

Thanks.

Upvotes: 1

Pankaj Shukla
Pankaj Shukla

Reputation: 2672

If Shape() function was operating on x,y and doing some validation/manipulation on x,y then it would have made sense to pass x,y. The reason is that you wouldn't want to redo that work in Ball().

But because of simple assignments don't warrant passing x,y since x,y would anyways be attached to this object.

this.x = random(0,width);
this.y = random(0,height);

So, looks like it is not required to pass x,y.

Upvotes: 0

Related Questions