How to get a JavaScript object's class?

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

    Here's a implementation of getClass() and getInstance()

    You are able to get a reference for an Object's class using this.constructor.

    From an instance context:

    function A() {
      this.getClass = function() {
        return this.constructor;
      }
    
      this.getNewInstance = function() {
        return new this.constructor;
      }
    }
    
    var a = new A();
    console.log(a.getClass());  //  function A { // etc... }
    
    // you can even:
    var b = new (a.getClass());
    console.log(b instanceof A); // true
    var c = a.getNewInstance();
    console.log(c instanceof A); // true
    

    From static context:

    function A() {};
    
    A.getClass = function() {
      return this;
    }
    
    A.getInstance() {
      return new this;
    }
    
    0 讨论(0)
  • 2020-11-22 16:07

    I find object.constructor.toString() return [object objectClass] in IE ,rather than function objectClass () {} returned in chome. So,I think the code in http://blog.magnetiq.com/post/514962277/finding-out-class-names-of-javascript-objects may not work well in IE.And I fixed the code as follows:

    code:

    var getObjectClass = function (obj) {
            if (obj && obj.constructor && obj.constructor.toString()) {
                
                    /*
                     *  for browsers which have name property in the constructor
                     *  of the object,such as chrome 
                     */
                    if(obj.constructor.name) {
                        return obj.constructor.name;
                    }
                    var str = obj.constructor.toString();
                    /*
                     * executed if the return of object.constructor.toString() is 
                     * "[object objectClass]"
                     */
                     
                    if(str.charAt(0) == '[')
                    {
                            var arr = str.match(/\[\w+\s*(\w+)\]/);
                    } else {
                            /*
                             * executed if the return of object.constructor.toString() is 
                             * "function objectClass () {}"
                             * for IE Firefox
                             */
                            var arr = str.match(/function\s*(\w+)/);
                    }
                    if (arr && arr.length == 2) {
                                return arr[1];
                            }
              }
              return undefined; 
        };
        
    
    0 讨论(0)
  • 2020-11-22 16:09

    There's no exact counterpart to Java's getClass() in JavaScript. Mostly that's due to JavaScript being a prototype-based language, as opposed to Java being a class-based one.

    Depending on what you need getClass() for, there are several options in JavaScript:

    • typeof
    • instanceof
    • obj.constructor
    • func.prototype, proto.isPrototypeOf

    A few examples:

    function Foo() {}
    var foo = new Foo();
    
    typeof Foo;             // == "function"
    typeof foo;             // == "object"
    
    foo instanceof Foo;     // == true
    foo.constructor.name;   // == "Foo"
    Foo.name                // == "Foo"    
    
    Foo.prototype.isPrototypeOf(foo);   // == true
    
    Foo.prototype.bar = function (x) {return x+x;};
    foo.bar(21);            // == 42
    

    Note: if you are compiling your code with Uglify it will change non-global class names. To prevent this, Uglify has a --mangle param that you can set to false is using gulp or grunt.

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

    Question seems already answered but the OP wants to access the class of and object, just like we do in Java and the selected answer is not enough (imho).

    With the following explanation, we can get a class of an object(it's actually called prototype in javascript).

    var arr = new Array('red', 'green', 'blue');
    var arr2 = new Array('white', 'black', 'orange');
    

    You can add a property like this:

    Object.defineProperty(arr,'last', {
      get: function(){
        return this[this.length -1];
      }
    });
    console.log(arr.last) // blue
    

    But .last property will only be available to 'arr' object which is instantiated from Array prototype. So, in order to have the .last property to be available for all objects instantiated from Array prototype, we have to define the .last property for Array prototype:

    Object.defineProperty(Array.prototype,'last', {
      get: function(){
        return this[this.length -1];
      }
    });
    console.log(arr.last) // blue
    console.log(arr2.last) // orange
    

    The problem here is, you have to know which object type (prototype) the 'arr' and 'arr2' variables belongs to! In other words, if you don't know class type (prototype) of the 'arr' object, then you won't be able to define a property for them. In the above example, we know arr is instance of the Array object, that's why we used Array.prototype to define a property for Array. But what if we didn't know the class(prototype) of the 'arr'?

    Object.defineProperty(arr.__proto__,'last2', {
      get: function(){
        return this[this.length -1];
      }
    });
    console.log(arr.last) // blue
    console.log(arr2.last) // orange
    

    As you can see, without knowing that 'arr' is an Array, we can add a new property just bu referring the class of the 'arr' by using 'arr.__proto__'.

    We accessed the prototype of the 'arr' without knowing that it's an instance of Array and I think that's what OP asked.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 16:12

    In javascript, there are no classes, but I think that you want the constructor name and obj.constructor.toString() will tell you what you need.

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