https://github.com/exebook/dnaof
I created this simple inheritance tool for JavaScript, could any one with deep knowledge in JavaScript prototyped inheritance review it?
Here is the library itself:
kindof = function(K) {
function X() {}
if (K != undefined) X.prototype = new K
X.can = X.prototype
return X
}
dnaof = function(x, f) {
var p = x.__proto__
x.__proto__ = p.__proto__
var r = p.__proto__[f].apply(x)
x.__proto__ = p
return r
}
And here is the example usage to demonstrate what it can do:
require('./dnaof')
// create a kind of idiot without ancestor:
var idiot = kindof()
// tell what it can do:
idiot.can.say = function() { return this.name + ' can chat' }
idiot.can.rest = function() { console.log('bzzzz.z.z.z... (' + this.name + ')') }
// a new kind of smart inherits from a kind of idiot
var smart = kindof(idiot)
// he can also say something:
smart.can.say = function() {
// he can say something new, and he can say the same thing as an idiot can:
return dnaof(this, 'say') + ', ' + this.name + ' can talk'
}
// a kind of a genious can do the same things as an idiot and smart can, and even more:
var genious = kindof(smart)
genious.can.say = function() {
return dnaof(this, 'say') + ', ' + this.name + ' can discuss'
}
// instantiate three persons:
var bob = new idiot
var alice = new smart
var candy = new genious
// assign properties, because to make life simpler we do not initialize anything during creation:
bob.name = 'bob'
alice.name = 'alice'
candy.name = 'candy'
// let them talk:
console.log(bob.say())
console.log(alice.say())
console.log(candy.say())
// let them take some rest:
alice.rest(), bob.rest(), candy.rest()
__proto__
is non-standard. See here developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… \$\endgroup\$new
to setup the prototype chain, you can useObject.create
in every modern browsers. Also, to dynamically get the parent class, you can doObject.getPrototypeOf(Object.getPrototypeOf(this))
. With these changes you can stop using__proto__
. Also, you should opt for a syntax that doesn't require you to writeobj.can
all the time to define new members. \$\endgroup\$