Iterate Constructor Chain Up

后端 未结 2 705
旧时难觅i
旧时难觅i 2021-01-21 09:20

Assuming I have something like this:

function A() {}

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

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


        
相关标签:
2条回答
  • 2021-01-21 09:28

    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.

    0 讨论(0)
  • 2021-01-21 09:44

    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.

    0 讨论(0)
提交回复
热议问题