Created
June 5, 2014 14:30
-
-
Save tamaspap/3d555e554a270db4e886 to your computer and use it in GitHub Desktop.
JS inheritance with Object.create
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() { | |
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