Get parent class name from child with ES6?

前端 未结 4 1303
野性不改
野性不改 2020-11-29 08:16

I would like to get the parent class name (Parent), but I\'m only able to retrieve the child class name with this code (Child)...

相关标签:
4条回答
  • 2020-11-29 08:37

    From proto property:

    Child['__proto__'].name
    

    example here: https://stackblitz.com/edit/typescript-s5brk9

    0 讨论(0)
  • 2020-11-29 08:46

    You could technically do

    // instanceProto === Child.prototype
    var instanceProto = Object.getPrototypeOf(instance);
    
    // parentProto === Parent.prototype
    var parentProto = Object.getPrototypeOf(instanceProto);
    console.log(parentProto.constructor.name);
    

    keep in mind that these names may all be mangled by minifiers.

    0 讨论(0)
  • 2020-11-29 08:47

    ES6 classes inherit from each other. So when instance.constructor refers to the Child, then you can use Object.getPrototypeOf(instance.constructor) to get the Parent, and then access .name:

    Object.getPrototypeOf(instance.constructor).name // == "Parent"
    

    Of course, full ES6 compliance and non-minified code are necessary for this to work. You should never rely on function names in code.

    0 讨论(0)
  • 2020-11-29 08:59

    Here is something amusing:

    class J {}
        
    class K extends J {}
    
    class L extends K {}
    
    function getBaseClass(targetClass){
      if(targetClass instanceof Function){
        let baseClass = targetClass;
    
        while (baseClass){
          const newBaseClass = Object.getPrototypeOf(baseClass);
    
          if(newBaseClass && newBaseClass !== Object && newBaseClass.name){
            baseClass = newBaseClass;
          }else{
            break;
          }
        }
    
        return baseClass;
      }
    }
    
    console.log(getBaseClass(L)); // Will return J.

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