How to get a JavaScript object's class?

前端 未结 18 2349
一生所求
一生所求 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:06

    Here's a implementation of getClass() and getInstance()

    You are able to get a reference for an Object's class using this.constructor.

    From an instance context:

    function A() {
      this.getClass = function() {
        return this.constructor;
      }
    
      this.getNewInstance = function() {
        return new this.constructor;
      }
    }
    
    var a = new A();
    console.log(a.getClass());  //  function A { // etc... }
    
    // you can even:
    var b = new (a.getClass());
    console.log(b instanceof A); // true
    var c = a.getNewInstance();
    console.log(c instanceof A); // true
    

    From static context:

    function A() {};
    
    A.getClass = function() {
      return this;
    }
    
    A.getInstance() {
      return new this;
    }
    

提交回复
热议问题