Skip to content

Instantly share code, notes, and snippets.

@svanellewee
Last active August 29, 2015 14:04
Show Gist options
  • Save svanellewee/22332046b164ffc6b1a2 to your computer and use it in GitHub Desktop.
Save svanellewee/22332046b164ffc6b1a2 to your computer and use it in GitHub Desktop.
inheritance, instanceof
var pp = console.log
function Base(name) {
this.name = name || "unnamed"
}
Base.prototype.giveName= function() {
return "[["+ this.name +"]]"
}
function DataBase(name) {
Base.call(this,name);
// this.constructor = DataBase // just to make instanceof be accurate
}
DataBase.prototype = new Base()
//DataBase.constructor = DataBase
var db =new DataBase("bob")
pp(db.giveName())
var db =new DataBase()
pp(db.giveName())
var goodClassCheck = [(db instanceof Base) , (db instanceof DataBase) ]
pp( goodClassCheck ) // [ T, T]
var anotherClassCheck = [(db instanceof DataBase),
(DataBase.prototype instanceof Base) ,
(Base.prototype instanceof Object)] // the prototype chain!
pp( anotherClassCheck); // [ T, T, T]
// prototype is not a value in the db object! It is in the prototype chain!
//
/**
var badAnotherClassCheck2 = [(db instanceof DataBase),
(db.prototype.prototype instanceof Base) ,
(db.prototype.prototype.prototype instanceof Object)]
*/
// the prototype chain again
pp(">>", Object.getPrototypeOf) // native code
var betterAnotherClassCheck2 = [ (db instanceof DataBase),
(Object.getPrototypeOf(db) === DataBase.prototype),
(Object.getPrototypeOf(DataBase.prototype) === Base.prototype ),
(Object.getPrototypeOf(Base.prototype) === Object.prototype) ];
pp(betterAnotherClassCheck2); // [T, T, T, T]
@svanellewee
Copy link
Author

I keep thinking classical OOP. Prototypes means "Classes" are just other objects!
var anotherClassCheck = [(db instanceof DataBase), (DataBase.prototype instanceof Base) , (Base.prototype instanceof Object)] //--> [ True True True ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment