JavaScript – Make a inheritance function

In JavaScript there are plenty of ways for inheritance. I can think of at least two. 🙂 However, a nice one is if you do everything “by the hand”. Thus, writing a function, that gets the inherited object and makes it a prototype of the new one. Thus, it works!

Pretty much in the demo, I have created four objects – v1, v2, v3, v4, each one inheriting the previous one. Then I am printing the properties of v3 and v4, to see what they have inherited.

output

Here comes the code:

function inherit(obj_parent){
    if (obj_parent == null){
        throw TypeError;
    }

    if (Object.create){
        return Object.create(obj_parent);
    }

    if (typeof obj_parent !== "function" && typeof obj_parent !== "object"){
        throw TypeError;
    }

    function child(){};
    child.prototype = obj_parent;
    return new child();
}


var v1 = {};
v1.a = 5;

var v2 = inherit(v1);
v2.b = 10;

var v3 = inherit(v2);
v3.c = 15;

var v4 = inherit(v3);
v4.d = "vitoshacademy.com";

document.write(v3.a + "<br>");
document.write(v3.b + "<br>");
document.write(v3.c + "<br>");
document.write(v4.d + "<br>");

Not a lot, eh? 🙂