Skip to content

Instantly share code, notes, and snippets.

@rupert-ong
Created October 27, 2018 17:36
Show Gist options
  • Save rupert-ong/077e8cc1c84f50f7d74891787a3e47a1 to your computer and use it in GitHub Desktop.
Save rupert-ong/077e8cc1c84f50f7d74891787a3e47a1 to your computer and use it in GitHub Desktop.
JavaScript: Classical Inheritance with Object.create() #javascript #prototype #es5 #inheritance #object #create
var MyShape = function (x, y) {
this.x = x;
this.y = y;
}
MyShape.prototype.move = function(xOffset, yOffset){
this.x += xOffset;
this.y += yOffset;
console.log(`MyShape instance moved to ${this.x}, ${this.y}.`);
}
var MyRectangle = function(w, h) {
MyShape.call(this, 0, 0);
this.width = w;
this.height = h;
}
MyRectangle.prototype = Object.create(MyShape.prototype);
MyRectangle.prototype.constructor = MyRectangle;
MyRectangle.prototype.draw = function(){
console.log(`MyRectangle instance drawn at (x,y) of (${this.x}, ${this.y}) and a (w, h) of (${this.width}, ${this.height})`);
};
let r1 = new MyRectangle(100, 200);
r1.move(5, 10);
r1.draw();
console.log(r1 instanceof MyRectangle, r1 instanceof MyShape);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment