I know how to create subclass prototypes from superclass prototypes. But what if I already have an instance of the superclass object to make a subclass object from?
Using MDN example for classic OOP in JS:
// Shape - superclass
function Shape(x, y) {
this.x = x;
this.y = y;
}
// Rectangle - subclass
function Rectangle(x, y, w, h) {
Shape.call(this, x, y); // call super constructor.
this.w = w;
this.h = h;
}
// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
What if I already have an instance of a shape and I want to create a rectangle based on that?
function createSquareFromShape(shape) {
var rect = new Rectangle(1, 1);
rect = Object.create(shape);
// rect gets the shape prototype but loses Rectangle
}
I know I can manually copy properties from one object to another but maybe there's a faster and easier way?