Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate Constructor Chain Up

Tags:

javascript

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.

like image 659
anderswelt Avatar asked Jul 16 '26 15:07

anderswelt


1 Answers

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.

like image 80
Bergi Avatar answered Jul 18 '26 05:07

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!