

This is useful because it allows you to get the name of the class that created an object, which can be useful for debugging. In this post, we'll learn how you can get the class name of an object in JavaScript by using the constructor property. The reason this works is you can use the constructor property to get the class of an object, which includes the name, along with other properties.īecause most things in JavaScript are objects, they will therefore have a valid constructor property. Getting the class name of an objectįirst let's start with a class and an object created from it.

In this post, we'll learn how you can get the class name of an object in JavaScript. One useful thing to be able to know from an object is the name of the class it was created from.
Get the class attribute of the firstIf (obj & obj.constructor & supports object-oriented programming, which means that you can create classes and objects, and use them to store data. The className property sets or returns an elements class attribute. If you want to get the class name as a string, I found the following working well: Note that Dog is a constructor function, and is a Function object. To get the "pseudo class", you can get the constructor function, by obj.constructorĪssuming the constructor is set correctly when you do the inheritance - which is by something like: Dog.prototype = new Animal() Īnd these two lines, together with: var woofie = new Dog() Or just compare the constructors themselves, however this won't work across DOM boundaries as there are different instances of the constructor function on each DOM. For example instead of checking if = "MyType", instead check = MyType.name. The only cases where it fails are if an object is created without a prototype, via Object.create( null ), or the object was instantiated from an anonymously-defined (unnamed) function.Īlso note that if you are minifying your code, it's not safe to compare against hard-coded type strings. It will return "Number" for numbers, "Array" for arrays and "Function" for functions, etc. If the object is instantiated with var obj = new M圜lass(), it will return "M圜lass". Function.name was officially added to the standard in ES6, making this a standards-compliant means of getting the "class" of a JavaScript object as a string.
