0

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.

kmiklas
  • 13,085
  • 22
  • 67
  • 103
  • Why would you want to do this? – Pointy Jan 31 '14 at 04:21
  • I'm writing a new library. – kmiklas Jan 31 '14 at 04:26
  • There is no programmatic way to go down the prototype chain (Children of parent) as far as I know you can only go up. Please do not create an instance of Parent to set the prototype part of Child and call `Parent.apply(this,arguments)` in Child body or better yet; pass an object as parameters and call `Parent.call(this,parms);` as demonstrated here: http://stackoverflow.com/a/16063711/1641941 You could try `Cheese.descendants=[Cheddar,Brie,...]` and manually maintain a reference down the prototype chain. – HMR Jan 31 '14 at 06:25
  • Thank you! Let me know if you're interested in viewing the repo and I'll send you the Git address when it's published. It's an object-oriented mobile/responsive positioning system. – kmiklas Jan 31 '14 at 14:37

0 Answers0