Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tamaspap/3d555e554a270db4e886 to your computer and use it in GitHub Desktop.
Save tamaspap/3d555e554a270db4e886 to your computer and use it in GitHub Desktop.
JS inheritance with 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();
rect instanceof Rectangle // true.
rect instanceof Shape // true.
rect.move(1, 1); // Outputs, "Shape moved."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment