Skip to content

Instantly share code, notes, and snippets.

@branneman
Last active October 18, 2021 06:18
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save branneman/c81f9969ccab9ea9cd1c to your computer and use it in GitHub Desktop.
Save branneman/c81f9969ccab9ea9cd1c to your computer and use it in GitHub Desktop.
ES3 & ES5 — Prototypal Inheritance
/**
* Parent
*/
function Shape(x, y) {
this.x = x;
this.y = y;
}
Shape.prototype.constructor = Shape;
Shape.prototype.pos = function() {
return [this.x, this.y];
};
/**
* Child
*/
function Rect(x, y, w, h) {
Shape.call(this, x, y);
this.w = w;
this.h = h;
}
////////////////////////////////////////////////////////////////////////////////
// Inheritance: solution 1
Rect.prototype = Object.create(Shape.prototype);
Rect.prototype.constructor = Rect;
// Inheritance: solution 2
var f = function() {};
f.prototype = Shape.prototype;
Rect.prototype = new f();
Rect.prototype.constructor = Rect;
// Inheritance: solution 3
var p = {};
p.__proto__ = Shape.prototype;
Rect.prototype = p;
Rect.prototype.constructor = Rect;
////////////////////////////////////////////////////////////////////////////////
// Add a method to the rect object.
Rect.prototype.area = function() {
return this.w * this.h;
};
/**
* Example usage
*/
var s = new Shape(10, 20);
var r1 = new Rect(30, 30, 5, 10);
var r2 = new Rect(10, 20, 15, 15);
s.constructor; //=> Shape
s.pos(); //=> [10, 20]
r1.constructor; //=> Rect
r1.pos(); //=> [30, 30]
r1.area(); //=> 50
r2.constructor; //=> Rect
r2.pos(); //=> [10, 20]
r2.area(); //=> 225
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment