How to get a JavaScript object's class?

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

    This getNativeClass() function returns "undefined" for undefined values and "null" for null.
    For all other values, the CLASSNAME-part is extracted from [object CLASSNAME], which is the result of using Object.prototype.toString.call(value).

    getAnyClass() behaves the same as getNativeClass(), but also supports custom constructors

    function getNativeClass(obj) {
      if (typeof obj === "undefined") return "undefined";
      if (obj === null) return "null";
      return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1];
    }
    
    function getAnyClass(obj) {
      if (typeof obj === "undefined") return "undefined";
      if (obj === null) return "null";
      return obj.constructor.name;
    }
    
    getClass("")   === "String";
    getClass(true) === "Boolean";
    getClass(0)    === "Number";
    getClass([])   === "Array";
    getClass({})   === "Object";
    getClass(null) === "null";
    
    getAnyClass(new (function Foo(){})) === "Foo";
    getAnyClass(new class Foo{}) === "Foo";
    
    // etc...
    

提交回复
热议问题