How to get a JavaScript object's class?

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

    I suggest using Object.prototype.constructor.name:

    Object.defineProperty(Object.prototype, "getClass", {
        value: function() {
          return this.constructor.name;
        }
    });
    
    var x = new DOMParser();
    console.log(x.getClass()); // `DOMParser'
    
    var y = new Error("");
    console.log(y.getClass()); // `Error'
    

提交回复
热议问题