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.
Here comes the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
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? 🙂