Skip to content

Instantly share code, notes, and snippets.

@EduardoSaverin
Last active February 14, 2018 13:25
Show Gist options
  • Save EduardoSaverin/fe3f5fa8b3baf1d973c6d1b231260e92 to your computer and use it in GitHub Desktop.
Save EduardoSaverin/fe3f5fa8b3baf1d973c6d1b231260e92 to your computer and use it in GitHub Desktop.
Showing Inheritance using Object.create and `new` Operator
// 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() {
// If we use new Shape() then properties are assigned in __proto__
// and still eveything will work.So no need to call Shape.call(this).
// But if we use Object.create(Shape.prototype) then properties x & y are not copied so
// we need to call Shape.call(this).
Shape.call(this); // call super constructor.
}
// subclass extends superclass
//Rectangle.prototype = new Shape(); // <-- This line doesn't require Shape.call(this);
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
var rect = new Rectangle();
// Do notice rect in console for right understanding.
var rect = new Rectangle();
console.log(rect);
console.log(rect.move(1,2));
@EduardoSaverin
Copy link
Author

Some Links that I found useful :

JS Bits
A drip of JavaScript

Object.assign

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment