Javascript: How to get a list of object prototype circuit constructors names?

I recently ran into an interesting problem. I am developing using some existing code, where, for better or worse, there are often several levels of prototypical inheritance, ending with constructors for all kinds of different objects. Each of them ultimately inherits from one base class.

Each constructor follows the following inheritance pattern, where it Subis a subclass, and Superis a direct prototype:

function Sub(/*args*/) {
    Super.call(this,/*args*/);
}

Sub.prototype = Object.create(Super.prototype);

This pattern extends up to one base class.

The finding that it would be extremely useful for our needs to keep a list of names of designers for each object in the prototype chain, I came up with the following code completion for the base class, which uses calleeand callerproperties of the object the arguments :

var curConstructor = arguments.callee;
this.constructorList = [curConstructor.name];

while(curConstructor.caller && curConstructor.caller.name !== ''){
    curConstructor = curConstructor.caller;
    this.constructorList.push(curConstructor.name);
}

The main problem with this is that it only works if the object was created inside an anonymous function (or global scope). For example, if I have a SubA1prototype constructor SubAwith a prototype Base, if I do this:

function() {
  var aOk = new SubA1();
  function oops() {
    var aNotOk = new SubA1();
  }
  oops();
}

aOklist of constructors: [Base,SubA,SubA1]what I want.

aNotOka list of constructors ends up as: [Base,SubA,SubA1,oops].

Here is the plunker .

, , , - ( /) -.

?

, Node.js, Node.js. , Node.

:

. , , , , constructorList.

, :

var curConstructor = arguments.callee;
this.constructorList = [curConstructor.name];

while(curConstructor.caller){
    curConstructor = curConstructor.caller;

    // Exit if the function name isn't part of the namespace
    if(typeof namespace[curConstructor.name] !== 'function') break;

    this.constructorList.push(curConstructor.name);
}

, , , . , new SubA1, , , . , , .

, arguments.callee , Object.constructor ( , ), , .

+4
1

, :

function getConstructorChain(obj, type) {
    var cs = [], pt = obj;
    do {
       if (pt = Object.getPrototypeOf(pt)) cs.push(pt.constructor || null);
    } while (pt != null);
    return type == 'names' ? cs.map(function(c) {
        return c ? c.toString().split(/\s|\(/)[1] : null;
    }) : cs;
}

type , type = 'names' - .

FIDDLE HTMLDivElement . .

+2

All Articles