Chapter 6 - Objects

6.2.2 Inhertiance

by Denise Nepraunig

JavaScript

// JavaScript The Definitive Guide 6th Edition
// 6.2.2 Inheritance

// inheritance chain: if an object, doesn't have a certain
// property the prototpye chain is 'walked up' to find it

var o = {};
o.x = 1;
var p = inherit(o);
p.y = 2;
var q = inherit(p);
q.z = 3;

q.x = 5; // now we override the inherited version and now 
// we have our own x, if we delete it, the inherited x comes back

var s = q.toString();

var sum = q.x + q.y;
console.log(sum);

var unitcircle = { r: 1 };
var c = inherit(unitcircle);
c.x = 1; c.y = 1;
c.r = 2; // now we have our own r, we override it the inherited prop.

console.log("unitcircle.r", unitcircle.r);

// here our own inherit function
function inherit(p) {
    if (p == null) throw TypeError();
    if (Object.create)
        return Object.create(p);
    // here polyfill stuff
    var t = typeof p;
    if (t !== "object" && t !== "function") throw TypeError();
    function f() {}; // dummy constructor
    f.prototpye = p; // set prototype
    return new f(); // use f() to create an 'heir' of p (Erben)
}