Skip to content

Instantly share code, notes, and snippets.

@ErnWong
Created December 14, 2012 04:38
Show Gist options
  • Save ErnWong/4282725 to your computer and use it in GitHub Desktop.
Save ErnWong/4282725 to your computer and use it in GitHub Desktop.
Javascript Inheritance in Different Ways.
// Parent:
function Book() {
// there could be a lot of things here
};
Book.prototype.read = function( lowerLimit, upperLimit ) {};
// 1.
function BIGBook() {};
BIGBook.prototype.read = Book.prototype.read;
BIGBook.prototype.ripPages = function( lowerLimit, upperLimit ) {};
(new BIGBook()) instanceof Book; // false. not-so-true inheritance
// 2.
function Dictionary() {};
Dictionary.prototype = new Book(); // Downside: calling constructor when we only want the instanceof
Dictionary.prototype.find = function( key ) {};
(new Dictionary()) instanceof Book; // true
// to overcome downside:
var inheriting = false;
Dictionary = function() {
if ( ! inheriting ) {
this.init(); // where init is the actual constructor of this "class"
}
} // John Resig's idea from http://ejohn.org/blog/simple-javascript-inheritance/
function PocketDictionary() {};
inheriting = true;
PocketDictionary.prototype = new Dictionary();
inheriting = false;
// ..do my stuff...
// to overcome downside (second approach):
var tmp = function() {};
tmp.prototype = Book.prototype;
function TextBook() {};
TextBook.prototype = new tmp();
TextBook.prototype.scribble = function( complexity, size, location ) {};
/* Second Downside:
* On Google Chrome's Console...
* > new Dictionary()
* v Dictionary
* v __proto__: Book (Should be Dictionary, not Book)
* > find: function( key ) {}
* v __proto__: Book
* > constructor: function Book() {
* > read: function(... etc
*/
// 3.
function ExerciseBook() {};
ExerciseBook.prototype = Book.prototype;
ExerciseBook.prototype = new ExerciseBook(); // bad if ExerciseBook is a big, long, constructor. Can be fixed like Resig's idea.
ExerciseBook.prototype.write = function( page, line, content ) {};
(new ExerciseBook()) instanceof Book; // true
// On Google Chrome's Console...
/*
* > new ExerciseBook()
* v ExerciseBook
* v __proto__: ExerciseBook (Yay! It looks better)
* > write: function( key ) {}
* v __proto__: Book
* > constructor: function Book() {
* > read: function(... etc
*/
// Is there anything bad about 3?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment