3

Assuming I have something like this:

function A() {}

function B() {}
B.prototype = Object.create(A.prototype);

function C() {}
C.prototype = Object.create(B.prototype);

var inst = new C();

I can now do inst instanceof C == true, inst instanceof B == true, instanceof C == true.

But how could I "iterate" the constructor functions up starting from the instance of C() so that it'd return function C(), function B(), function A() which I could then use to instantiate another instance.

anderswelt
  • 1,482
  • 1
  • 12
  • 23

2 Answers2

3

You can iterate the prototypes by doing

for (var o=inst; o!=null; o=Object.getPrototypeOf(o))
    console.log(o);
// {}
// C.prototype
// B.prototype
// A.prototype
// Object.prototype

However, that will only iterate the prototype chain. There is no such thing as a "constructor chain". If you want to access the constructors, you will need to set the .constructor property on the prototypes appropriately when inheriting:

function A() {}

function B() {}
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;

function C() {}
C.prototype = Object.create(B.prototype);
C.prototype.constructor = C;

var inst = new C();

for (var c=inst.constructor; c!=null; (c=Object.getPrototypeOf(c.prototype)) && (c=c.constructor))
    console.log(c);
// C
// B
// A
// Object

which I could then use to instantiate another instance

You would only need to know of C for that, not of the "chain". You may access it via inst.constructor if you have set C.prototype.constructor correctly.

However, it might be a bad idea to instantiate objects from arbitrary constructors; you don't know the required parameters. I don't know what you actually want to do, but your request might hint at a design flaw.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

Go up the chain using the constructor property of the object's prototype.

For example, after your code:

 C.prototype.constructor === A

is true, as is

  inst.constructor.prototype.constructor === A

... and so forth.

BadZen
  • 4,083
  • 2
  • 25
  • 48