mr.goofy33
mr.goofy33

Reputation: 9

javascript prototype property

I have a short question about prototypes.

An object that has the prototype of a Square function inherits the prototype of a Rectangle function, but of course not all rectangles are squares.Suppose an instance of Rectangle has its own properties width and height changed so that it becomes a square, how can this instance inherit the Square prototype when it is actually a square? Also, given a Square instance, how can it lose the Square prototype when it is no longer a square?

Upvotes: -1

Views: 64

Answers (1)

Quentin
Quentin

Reputation: 944320

It can't. Inheritance doesn't work like that.

In general, if you were creating a Square that inherited from a Rectangle, then it would override the functions for setting the height and width so that setting one would set the other and it could never be anything other than a square (and a Rectangle with equal sides would be square by coincidence and not in code).

If you want an object where sometimes it behaves differently if the height and width are the same, then put a test like if (this.height === this.width) in the functions where that matters.

Upvotes: 2

Related Questions