Created
January 11, 2012 19:16
-
-
Save doubleclickdetroit/1596267 to your computer and use it in GitHub Desktop.
JS Inheritance
This file contains 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
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 |
This file contains 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
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