1

This code is from the MDN article on Object.create():

// Shape - superclass
function Shape() {
  this.x = 0;
  this.y = 0;
}

// superclass method
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};

// Rectangle - subclass
function Rectangle() {
  Shape.call(this); // call super constructor.
}

// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

The third to last line is the one that I'm confused about.

What would be the difference between:

A. how it is now.
B. Rectangle.prototype = Object.create(Shape);
C. Rectangle.prototype = new Shape();

Wouldn't all 3 ultimately yield the same result? The same attributes defined on rect and the same use of memory to define them?

Yes, I have read the other StackOverflow questions addressing Object.create(). No, they did not fully address my confusion.

temporary_user_name
  • 35,956
  • 47
  • 141
  • 220

1 Answers1

3
  • Object.create(Shape) returns an object which inherits from Shape.

    If you want to make a subclass of Shape, you probably don't want to do this.

  • Object.create(Shape.prototype) returns an object which inherits from Shape.prototype.

    Therefore, this object will not have the x and y own properties.

  • new Shape() does this:

    1. Creates an object which inherits from Shape.prototype.
    2. Calls Shape, passing the previous object as this.
    3. Returns that object (assuming Shape didn't return another object).

    Therefore, this object will have the x and y own properties.

Oriol
  • 274,082
  • 63
  • 437
  • 513
  • 2
    You probably should mention that one *doesn't want* the prototype object to have own `x` and `y` properties… – Bergi Jan 22 '15 at 01:00
  • I just don't understand what happens when you call `Object.create(Shape)`. I get that it doesn't work but I don't know why. If you take out the line `Shape.call(this)` and use `Object.create(Shape)` instead of `Object.create(Shape.prototype)`, then instantiate a `Rectangle`, the resulting object has neither `x` nor `y` nor `move`. So what happened? What is being set as what? – temporary_user_name Jan 22 '15 at 01:48
  • 1
    @Aerovistae The problem is that, since `Shape` is a function, `Object.create(Shape)` inherits from `Shape` (which has no own property), `Function.prototype`, and `Object.prototype`. However, you are trying to subclass `Shape`. That means you want to inherit from `Shape.prototype` (which has the `move` method), and `Object.prototype`. – Oriol Jan 22 '15 at 01:52