4

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?

  • It's possible but [not recommended](http://stackoverflow.com/q/23807805/1048572). You really should create a new object instead: `new Rect(shape.x, shape.y, 1, 1)` – Bergi Oct 14 '16 at 13:40

1 Answers1

-1

Object.create returns a new object with its prototype set to whatever object you passed in as the first parameter to the create method. So you are overwriting your rect variable with a new object.

You won't be able to create a Rectangle object from a Shape object, since you Rectangle is a specialization of your Shape object, Shape does not know in which manner it was specialized.

If you are determined to learn a class based style for JavaScript, I would suggest a function on your Shape "class" (object) which creates Rectangles from it self. Or a factory that can take a Shape and return a Rectangle, along the lines of

var ShapeFactory = {
    CreateRectange: function(shape, w, h) {
        var rect = new Rectangle();
        rect.x = shape.x;
        rect.y = shape.y;
        rect.w = w;
        rect.h = h;
        return rect;
    }
}

var shape = new Shape(1,1);
var rect = ShapeFactory.CreateRectangle(shape, 1, 1);

I feel that I need to suggest reading this book series https://github.com/getify/You-Dont-Know-JS specifically https://github.com/getify/You-Dont-Know-JS/tree/master/this%20%26%20object%20prototypes and decide for yourself if it is worth learning the class based pattern (this can be a very polarizing topic in the community)

Heinrich Henning
  • 933
  • 5
  • 15
  • I specifically wanted to avoid manually setting properties, but thank you very much because, yes, I do tend to agree more and more that class based patterns in JS are sort of against the philosophy of JS. – user1533299 Oct 14 '16 at 13:56