Inheritance Models in Javascript

Posted Saturday, May 21, 2022 by Sri. Tagged MEMO

Just screwing around here.

Prototypal Single Inheritance

The original Javascript 1.0 model! All objects in Javascript inherit from a 'prototype' object, so you can "chain" objects together as you create them. In the old days you would directly set the __proto__ property, but modern JS provides a new API method Object.setPrototypeOf()

const ROOT = {
'GLOBAL': 'Global',
'agent': 'Agent'
};
const A = {
'Bees': 'Bees',
'Flowers': 'Flowers'
};
const B = {
'Magic': 'Magic'
};
Object.setPrototypeOf(A, ROOT);
Object.setPrototypeOf(B, A);

// prints Global, because B inherits from A which inherits from ROOT
console.log(B.GLOBAL); // value of GLOBAL is Global

// prints everything in the inheritance chain, because that's how the
// ancient key in object syntax works, and is not usually desirable
for (key in B) console.log(key); // GLOBAL, agent, Bees, Flowers, Magic

// prints only Magic, because Object.keys() only looks at 'own' properties
Object.keys(B).forEach(key=>console.log(key));