How to get a JavaScript object's class?

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

提交回复
热议问题