Skip to content

Instantly share code, notes, and snippets.

@ralphtheninja
Last active December 10, 2015 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ralphtheninja/4432221 to your computer and use it in GitHub Desktop.
Save ralphtheninja/4432221 to your computer and use it in GitHub Desktop.
testing different ways of inheriting in node
function Base () {}
Base.prototype = {
foo: function () {
console.log('.. in Base.foo()')
}
, dude: function () {
console.log('.. in Base.dude()')
}
}
console.log('Base.prototype', Base.prototype)
// inherit using __proto__.__proto__
function D1 () {
this.__proto__.__proto__ = Base.prototype
console.log('this.__proto__', this.__proto__) // this.__proto__ === D1.prototype
console.log('this.__proto__.__proto__', this.__proto__.__proto__)
}
// here it's ok to set the complete prototype object
D1.prototype = {
dude: function () {
console.log('.. in D1.dude()')
Base.prototype.dude.call(this)
}
}
console.log('D1.prototype', D1.prototype)
var d1 = new D1()
d1.dude()
// inherit using util.inherit()
var inherits = require('util').inherits
inherits(D2, Base)
function D2 () {}
// when using util.inherit() we have to set the methods on the prototype object,
// rather than defining the prototype object itself
D2.prototype.goo = function () {
console.log('.. in D2.goo()')
console.log('... and D2.super_', D2.super_)
console.log('... and D2.super_.prototype', D2.super_.prototype)
}
// this doesn't work because it will fuck up the prototype object that is setup
// with util.inherit(), hence the __proto__.__proto__ fix in the previous example
//D2.prototype = {
//goo: function () {}
//}
console.log('D2.prototype', D2.prototype);
var d2 = new D2()
d2.dude()
d2.goo()
// we can use the constructor property, which is set by util.inherits() if we want to
console.log(d2.constructor)
var dd = new d2.constructor()
dd.dude()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment