Skip to content

Instantly share code, notes, and snippets.

@jbeard4
Created April 22, 2012 23:26
Show Gist options
  • Save jbeard4/2467484 to your computer and use it in GitHub Desktop.
Save jbeard4/2467484 to your computer and use it in GitHub Desktop.

Javascript and prototypal inheritance

curl -s https://raw.github.com/gist/2467484/oop.js | node

var ClassA = function (name) {
if(arguments.length){
this.name = name
}
}
ClassA.prototype.setName = function (name) {
this.name = name
}
var ClassB = function (name, lastName) {
this.lastName = lastName
ClassB.super_.call(this, name)
}
inherits(ClassB, ClassA)
ClassB.prototype.setAge = function (age) {
this.age = age
}
var ClassC = function (age) {
this.age = age
}
ClassC.prototype = new ClassA()
ClassC.prototype.constructor = ClassA
ClassC.prototype.setLastName = function (lastName) {
this.lastName = lastName
}
console.log('ClassB.prototype', ClassB.prototype) // correct
console.log('ClassC.prototype', ClassC.prototype) // wrong
// https://github.com/joyent/node/blob/master/lib/util.js#L498
// here just because you *should* know how it works.
function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment