Methods are usually added to the underlying prototype of an object so that they don't have to be stored in each instance that gets made later. That's the case in this example, the move()
function is being stored in Shape.prototype
.
If you don't use Shape.prototype
with Object.create()
, you won't get methods attached to that object inherited to Rectangle
.
Technically, you could use just Object.create(Shape)
, but only in situations where Shape only has instance properties attached directly to it and, even in that case, it wouldn't be a very scalable solution, because if you ever decided to go back and add methods to Shape.prototype
in the future, none of your sub-types would inherit it.
// Shape — superClass
function Shape() {
this.x = 0;
this.y = 0;
}
// Shape.prototype is a unique and specific instance of Object
// This particular instance is what Shape inherits from and is
// the reason why Shape will get a .toString() and a .valueOf()
// method.
console.log(Shape.prototype);
// This method is added to Shape.prototype. If you don't inherit
// from this, you won't inherit this method!!
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.info('Figure has rode out somewhere.');
};
function Rectangle() {
Shape.call(this);
}
// If we don't inherit from Shape.prototype, we won't get
// any of the methods attached to it!
Rectangle.prototype = Object.create(Shape);
var r = new Rectangle();
console.log(r.x, r.y); // Works just fine for instance properties attached direclty to Shape
r.move(10,20); // Fails because Shape.prototype wasn't used for inheritance!