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
You can iterate over 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, 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))
console.log(c);
// 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.
source to share