Skip to content

Instantly share code, notes, and snippets.

@kevinpang
Created June 8, 2011 22:30
Show Gist options
  • Save kevinpang/1015599 to your computer and use it in GitHub Desktop.
Save kevinpang/1015599 to your computer and use it in GitHub Desktop.
JavaScript prototypal inheritance
function Shape(x, y) {
this.x = x;
this.y = y;
}
Shape.prototype.toString = function() {
return 'Shape at ' + this.x + ', ' + this.y;
};
function Circle(x, y, r) {
Shape.call(this, x, y); // invoke the base class's constructor function to take co-ords
this.r = r;
}
Circle.prototype = new Shape();
Circle.prototype.toString = function() {
return 'Circular ' + Shape.prototype.toString.call(this) + ' with radius ' + this.r;
}
var c = new Circle(1, 2, 3);
console.log(c.toString()); // "Circular Shape at 1, 2 with radius 3"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment