Skip to content

Instantly share code, notes, and snippets.

@doubleclickdetroit
Created January 11, 2012 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save doubleclickdetroit/1596267 to your computer and use it in GitHub Desktop.
Save doubleclickdetroit/1596267 to your computer and use it in GitHub Desktop.
JS Inheritance
function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
return this.name;
};
function Author(name, books) {
Author.superClass.constructor.call(this, name);
this.books = books;
}
extend(Author, Person);
Author.prototype.getBooks = function() {
return this.books;
};
Author.prototype.getName = function() {
var name = Author.superclass.getName.call(this);
return name + ", Author of " + this.getBooks().join(', ');
};
// example
var MichaelCrichton = new Author('Michael Crichton', ['Jurassic Park', 'The Andromeda Strain', 'Congo']);
console.log( MichaelCrichton.getName() ); // Michael Crichton, Author of Jurassic Park, The Andromeda Strain, Congo
function extend(subClass, superClass) {
var F = function() {};
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
subClass.superClass = superClass.prototype;
if (superClass.prototype.constructor == Object.prototype.constructor)
superClass.prototype.constructor = superClass;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment