Monday, September 29, 2008

Javascript Multiple Inheritance




Since this in the body of a function is the reference to the object used to call the function e.g.



obj.setProp = function(p) { this.prop = p }
obj.setProp(5)
obj.prop
=> 5

and since Javascript constructor function is the same as any other javascript function and the only difference happens through the use of the new operator. We can use this (double meaning) to inject functionality provided by multiple constructor functions (sort of multiple inheritance) into our own objects as long as the these constructor functions are not only natively implemented (e.g. Array, String, Function, .... etc) and that the injected functionalites are not dependent on their prototypes.



function Cat() { this.scratch = function () {alert("scratch!!")} }
function Dog() { this.bite = function () {alert("bite!!")} }
var catyDog = {}
catyDog.catify = Cat
catyDog.catify()
catyDog.dogify = Dog
catyDog.dogify()

Now the catyDog object can both scratch and bite, so you better be careful.



catyDog.scratch()
// alerts "scratch!!"

catyDog.bite()
// alerts "bite!!"

Another way of doing the same thing but keeping the injecting functions kind of private:



function CatyDog()
{
var me = this
this.myownProp = 'special prop'

var init = function() {
me.catify = Cat
me.dogify = Dog
me.catify()
me.dogify()
me.catify = undefined
me.dogigy = undefined
}
init()
}

Using such technique makes it our own responsibility to select which prototype of the constructors to choose for our own constructor and also to choose non-conflicting functionality which is always the case when using multiple inheritance.


In the previous example script if either Cat or Dog constructors had a prototype set, neither catify nor dogify will set the prototype for our object. Only the new operator would do such magic. So we will have to set the prototype of our choice ourselves using __proto__ property or we can set the prototype for our constructor function and rely on the new operator magic.


Now suppose that you need CatyDog to completely inherit Dog (including its prototype) while having Cat functionality.




function CatyDog()
{
var me = this
this.myownProp = 'special prop'

var init = function() {
me.catify = Cat
me.catify()
me.catify = undefined
}
init()
}
CatyDog.prototype = new Dog

var catyDog = new CatyDog

catyDog.scratch()
catyDog.bite()

The difference here is that any inherited Dog property including bite function will be fetched in the prototype each time it is used.

Also here all CatyDog objects will have one single prototype Dog object.
So if you need every object to have its own prototype object can do it this way



function CatyDog()
{
var me = this
this.myownProp = 'special prop'

var init = function() {
me.catify = Cat
me.catify()
me.catify = undefined
me.__proto__ = new Dog
}
init()
}

var catyDog = new CatyDog

catyDog.scratch()
catyDog.bite()

No comments: