Iterating constructor chaining

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();


Now I can execute inst instanceof C == true, inst instanceof B == true, instanceof C == true.

But how can I "iterate over" the constructor functions, starting with an instance of C () so that it returns a C () function, a B () function, a A () function, which I could then use to instantiate another instance.


source to share

2 answers

You can iterate over prototypes by doing

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


However, this will only repeat the prototype chain. There is no such thing as a "constructor chain". If you want to access constructors, you need to set a property.constructor

in prototypes 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))
// C
// B
// A
// Object


which I could use to instantiate another instance

You only need to know C

, not the "chain". You can access it via inst.constructor

if you have installed correctly C.prototype.constructor


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



Follow the chain using the object prototype constructor property.

For example, after your code:

 C.prototype.constructor === A


as true as

  inst.constructor.prototype.constructor === A


... etc.



All Articles