Johan Johan - 14 days ago 10
Javascript Question

Self executing function inheritance

I would like to know how to make

child
get the prototype methods from both itself and
base
.

Also, there any way to do

child.prototype = Object.create(base.prototype);
child.prototype.constructor = child;


inside of the
child
IIFE, rather than outside of it.

var base = (function(){

var cls = function(){

};

cls.prototype = {
doStuff: function(){
console.log('dostuff');
}
};

return cls;

})();

var child = (function(){

var cls = function(){
base.call(this);
};

cls.prototype = {
doOtherStuff: function(){
console.log('doOtherStuff');
}
};

return cls;

})();

child.prototype = Object.create(base.prototype);
child.prototype.constructor = child;

var b = new child();
b.doStuff();
b.doOtherStuff();


http://jsfiddle.net/9uGsA/

Answer

I would like to know how to make child get the prototype methods from both itself and base.

  1. Do child.prototype = Object.create(base.prototype); before setting up child prototype.
  2. Instead of doing cls.prototype = ..., add properties to cls.prototype one at a time.

Also, there any way to do [inheritance] inside of the child IIFE, rather than outside of it.

Of course, just use cls instead of child.

http://jsfiddle.net/7uCwz/

Bonus fiddle: http://jsfiddle.net/7uCwz/1/