2

I believe the best way would be something like:

var a = {a:1, b:2}
var b = Object.create(a);
b.a = 1
var c = Object.create(b);
c.c = 3;
var d = Object.create(c);

d.protoTree();  //returns: [c, b, a]
c.protoTree();  //returns: [b, a];
b.protoTree();  //returns: [a];

But is this possible? What's the best way assuming you only know the D object?

3 Answers3

2

You can use isPrototypeOf() for this use case

Arnav Kumar
  • 162
  • 2
  • 3
  • this method compares objects, but if i don't know that a, b, c exist, how can i use ``isPrototypeOf()``? –  Jan 08 '22 at 16:58
  • so at first check whether they exist or not then do the further checks – Arnav Kumar Jan 08 '22 at 17:03
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 08 '22 at 17:58
1

Using Object.prototype.isPrototypeOf() is the way to do this

function Person() {}
function Child() {}

Child.prototype = Object.create(Person.prototype);

const child = new Child();

console.log(Person.prototype.isPrototypeOf(child));

console.log(Child.prototype.isPrototypeOf(child));

More about Object.prototype.isPrototypeOf() here

Ran Turner
  • 14,906
  • 5
  • 47
  • 53
0

If wouldn't be good to have that as a member method, but it's easy to implement as a standalone (recursive) function:

function protoTree(obj){
    if(obj === null) return []
    return [obj, ...protoTree(Object.getPrototypeOf(obj))]
}

It works like this (note that it also returns Object.prototype, that a inherits from.

var a = {a:1, b:2}
var b = Object.create(a);
b.a = 1
var c = Object.create(b);
c.c = 3;
var d = Object.create(c);

//Note that `protoTree` returns the prototype objects themselves, not the variable names they are stored in
protoTree(d);  //returns: [c, b, a, Object.prototype]
protoTree(c);  //returns: [b, a, Object.prototype]
protoTree(b);  //returns: [a, Object.prototype]
protoTree(a);  //returns: [Object.prototype]
FZs
  • 16,581
  • 13
  • 41
  • 50
  • this spreading operator bugged my mind. –  Jan 08 '22 at 18:43
  • 1
    @RafaeldeSouza `[obj, ...protoTree(...)]` will create an array of `obj` and all the values returned by the recursive call. Without the spread, it would just put the returned *array* into the new array, so the result of calling `protoTree(d)` would be `[c, [b, [a, [Object.prototype, []]]]]`. Btw, `protoTree` can also be implemented without spread. – FZs Jan 08 '22 at 22:26