-1

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?

asked Feb 15, 2016 at 9:53
2
  • Objects don't "lose" prototypes like that (and "standard" OO inheritance also doesn't work that way). Your problem is actually a common one. Commented Feb 15, 2016 at 9:57
  • I an option you could consider is throwing an error in the width() & height() methods to ensure the values are set correctly depending on the shape criteria. Commented Feb 15, 2016 at 9:58

1 Answer 1

2

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.

answered Feb 15, 2016 at 9:56
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.