How to get a JavaScript object's class?

前端 未结 18 2185
一生所求
一生所求 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... );

    0 讨论(0)
  • 2020-11-22 16:17

    Agree with dfa, that's why i consider the prototye as the class when no named class found

    Here is an upgraded function of the one posted by Eli Grey, to match my way of mind

    function what(obj){
        if(typeof(obj)==="undefined")return "undefined";
        if(obj===null)return "Null";
        var res = Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1];
        if(res==="Object"){
            res = obj.constructor.name;
            if(typeof(res)!='string' || res.length==0){
                if(obj instanceof jQuery)return "jQuery";// jQuery build stranges Objects
                if(obj instanceof Array)return "Array";// Array prototype is very sneaky
                return "Object";
            }
        }
        return res;
    }
    
    0 讨论(0)
  • 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...
    
    0 讨论(0)
  • 2020-11-22 16:22

    In keeping with its unbroken record of backwards-compatibility, ECMAScript 6, JavaScript still doesn't have a class type (though not everyone understands this). It does have a class keyword as part of its class syntax for creating prototypes—but still no thing called class. JavaScript is not now and has never been a classical OOP language. Speaking of JS in terms of class is only either misleading or a sign of not yet grokking prototypical inheritance (just keeping it real).

    That means this.constructor is still a great way to get a reference to the constructor function. And this.constructor.prototype is the way to access the prototype itself. Since this isn't Java, it's not a class. It's the prototype object your instance was instantiated from. Here is an example using the ES6 syntactic sugar for creating a prototype chain:

    class Foo {
      get foo () {
        console.info(this.constructor, this.constructor.name)
        return 'foo'
      }
    }
    
    class Bar extends Foo {
      get foo () {
        console.info('[THIS]', this.constructor, this.constructor.name, Object.getOwnPropertyNames(this.constructor.prototype))
        console.info('[SUPER]', super.constructor, super.constructor.name, Object.getOwnPropertyNames(super.constructor.prototype))
    
        return `${super.foo} + bar`
      }
    }
    
    const bar = new Bar()
    console.dir(bar.foo)
    

    This is what that outputs using babel-node:

    > $ babel-node ./foo.js                                                                                                                   ⬡ 6.2.0 [±master ●]
    [THIS] [Function: Bar] 'Bar' [ 'constructor', 'foo' ]
    [SUPER] [Function: Foo] 'Foo' [ 'constructor', 'foo' ]
    [Function: Bar] 'Bar'
    'foo + bar'
    

    There you have it! In 2016, there's a class keyword in JavaScript, but still no class type. this.constructor is the best way to get the constructor function, this.constructor.prototype the best way to get access to the prototype itself.

    0 讨论(0)
  • 2020-11-22 16:23

    i had a situation to work generic now and used this:

    class Test {
      // your class definition
    }
    
    nameByType = function(type){
      return type.prototype["constructor"]["name"];
    };
    
    console.log(nameByType(Test));
    

    thats the only way i found to get the class name by type input if you don't have a instance of an object.

    (written in ES2017)

    dot notation also works fine

    console.log(Test.prototype.constructor.name); // returns "Test" 
    
    0 讨论(0)
  • 2020-11-22 16:26

    To get the "pseudo class", you can get the constructor function, by

    obj.constructor
    

    assuming the constructor is set correctly when you do the inheritance -- which is by something like:

    Dog.prototype = new Animal();
    Dog.prototype.constructor = Dog;
    

    and these two lines, together with:

    var woofie = new Dog()
    

    will make woofie.constructor point to Dog. Note that Dog is a constructor function, and is a Function object. But you can do if (woofie.constructor === Dog) { ... }.

    If you want to get the class name as a string, I found the following working well:

    http://blog.magnetiq.com/post/514962277/finding-out-class-names-of-javascript-objects

    function getObjectClass(obj) {
        if (obj && obj.constructor && obj.constructor.toString) {
            var arr = obj.constructor.toString().match(
                /function\s*(\w+)/);
    
            if (arr && arr.length == 2) {
                return arr[1];
            }
        }
    
        return undefined;
    }
    

    It gets to the constructor function, converts it to string, and extracts the name of the constructor function.

    Note that obj.constructor.name could have worked well, but it is not standard. It is on Chrome and Firefox, but not on IE, including IE 9 or IE 10 RTM.

    0 讨论(0)
提交回复
热议问题