Finding the prototype of a JavaScript object is fairly easy in a modern browser by simply using the Object.getPrototypeOf()
module.
Is there a function available which enables me to similarly find the immediate descendants of an instance? I imagine a getDescendantsOf()
or getInstancesOf()
module that returns all instances that exist in a given instance's prototype chain?
Think of like a jQuery .children()
function, except that we're instead traversing down a prototype chain instead of the DOM.
In the absence of a function, is there a best practice for accomplishing this?
Example:
var Cheese = function() {};
var Swiss = function() {};
Swiss.prototype = new Cheese();
var Cheddar = function() {};
Cheddar.prototype = new Cheese();
var Brie = function() {};
Brie.prototype = new Cheese();
var cheese = new Cheese(),
jarlsberg = new Swiss(),
cabotClothbound = new Cheddar(),
brillatAffine = new Brie();
console.dir(cheese); //-> Cheese
console.dir(jarlsberg); //-> Swiss
console.dir(Object.getPrototypeOf(jarlsberg)); //-> Cheese
Is there a function that would return the descendants of Cheese, maybe in an array? Something like this...
Object.getDescendantsOf(cheese); //-> [ Swiss, Cheddar, Brie ]?
Object.getInstancesOf(cheese); //-> [ jarlsberg, cabotClothbound, brillatAffine ]
tyvm.