Last active
February 14, 2018 13:25
-
-
Save EduardoSaverin/fe3f5fa8b3baf1d973c6d1b231260e92 to your computer and use it in GitHub Desktop.
Showing Inheritance using Object.create and `new` Operator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Some Links that I found useful :
JS Bits
A drip of JavaScript
Object.assign