Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a JavaScript object's class?

Tags:

javascript

oop

I created a JavaScript object, but how I can determine the class of that object?

I want something similar to Java's .getClass() method.

like image 280
DNB5brims Avatar asked Aug 08 '09 18:08

DNB5brims


People also ask

How do you find an object's class?

getClass() If an instance of an object is available, then the simplest way to get its Class is to invoke Object. getClass() .

How do you access a class in JavaScript?

Classes are declared with the class keyword. We will use function expression syntax to initialize a function and class expression syntax to initialize a class. We can access the [[Prototype]] of an object using the Object. getPrototypeOf() method.

What is object class in JavaScript?

The Object type represents one of JavaScript's data types. It is used to store various keyed collections and more complex entities. Objects can be created using the Object() constructor or the object initializer / literal syntax.


1 Answers

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.

like image 80
earl Avatar answered Sep 21 '22 06:09

earl