How to get a JavaScript object's class?

前端 未结 18 2382
一生所求
一生所求 2020-11-22 15:44

I created a JavaScript object, but how I can determine the class of that object?

I want something similar to Java\'s .getClass() method.

18条回答
  •  鱼传尺愫
    2020-11-22 16:23

    i had a situation to work generic now and used this:

    class Test {
      // your class definition
    }
    
    nameByType = function(type){
      return type.prototype["constructor"]["name"];
    };
    
    console.log(nameByType(Test));
    

    thats the only way i found to get the class name by type input if you don't have a instance of an object.

    (written in ES2017)

    dot notation also works fine

    console.log(Test.prototype.constructor.name); // returns "Test" 
    

提交回复
热议问题