How to get a JavaScript object's class?

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

    There is one another technique to identify your class You can store ref to your class in instance like bellow.

    class MyClass {
        static myStaticProperty = 'default';
        constructor() {
            this.__class__ = new.target;
            this.showStaticProperty = function() {
                console.log(this.__class__.myStaticProperty);
            }
        }
    }
    
    class MyChildClass extends MyClass {
        static myStaticProperty = 'custom';
    }
    
    let myClass = new MyClass();
    let child = new MyChildClass();
    
    myClass.showStaticProperty(); // default
    child.showStaticProperty(); // custom
    
    myClass.__class__ === MyClass; // true
    child.__class__ === MyClass; // false
    child.__class__ === MyChildClass; // true
    

提交回复
热议问题