Skip to content Skip to sidebar Skip to footer

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.proto

Solution 1:

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/


Solution 2:

Define a function http://jsfiddle.net/9uGsA/1/

function inherit(base, child, proto) {
    child.prototype = Object.create(base.prototype);
    child.prototype.constructor = child;

    proto&&Object.keys(proto).forEach(function(key){
        child.prototype[key] = proto[key];    
    })

}

and use it like this

var child = (function(){

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

    inherit(base, cls, {doOtherStuff: function(){
            console.log('doOtherStuff');
    }});


    return cls;

})();

Solution 3:

New simpler answer:

//test inheritance
//parent class
var mom = function(name){
    this.momsname = name;
}
mom.prototype.getMomsName = function(){ return this.momsname; }

//child class
var kid = function(mother,name){
    this.sonsname = name;
    //call the parent
    mom.call(this,mother);
}
//add the parent's methods
kid.prototype = new mom();
//point the constructor to the child
kid.prototype.constructor = kid;
kid.prototype.getKidsName = function() { return this.sonsname }
//instatiate the child
var son = new kid("Mary","Tom");
//use only the child's methods
var temp2 = "Son's name: " + son.getKidsName() + ". Mother's Name: " + son.getMomsName() + ".";
//temp now holds "Son's name: Tom. Mother's Name: Mary." 

Post a Comment for "Self Executing Function Inheritance"