How to get a JavaScript object's class?

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

    For Javascript Classes in ES6 you can use object.constructor. In the example class below the getClass() method returns the ES6 class as you would expect:

    var Cat = class {
    
        meow() {
    
            console.log("meow!");
    
        }
    
        getClass() {
    
            return this.constructor;
    
        }
    
    }
    
    var fluffy = new Cat();
    
    ...
    
    var AlsoCat = fluffy.getClass();
    var ruffles = new AlsoCat();
    
    ruffles.meow();    // "meow!"
    

    If you instantiate the class from the getClass method make sure you wrap it in brackets e.g. ruffles = new ( fluffy.getClass() )( args... );

提交回复
热议问题