Get the Name of an Object'S Type

Get the name of an object's type

Is there a JavaScript equivalent of Java's class.getName()?

No.

ES2015 Update: the name of class Foo {} is Foo.name. The name of thing's class, regardless of thing's type, is thing.constructor.name. Builtin constructors in an ES2015 environment have the correct name property; for instance (2).constructor.name is "Number".


But here are various hacks that all fall down in one way or another:

Here is a hack that will do what you need - be aware that it modifies the Object's prototype, something people frown upon (usually for good reason)

Object.prototype.getName = function() { 
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec((this).constructor.toString());
return (results && results.length > 1) ? results[1] : "";
};

Now, all of your objects will have the function, getName(), that will return the name of the constructor as a string. I have tested this in FF3 and IE7, I can't speak for other implementations.

If you don't want to do that, here is a discussion on the various ways of determining types in JavaScript...


I recently updated this to be a bit more exhaustive, though it is hardly that. Corrections welcome...

Using the constructor property...

Every object has a value for its constructor property, but depending on how that object was constructed as well as what you want to do with that value, it may or may not be useful.

Generally speaking, you can use the constructor property to test the type of the object like so:

var myArray = [1,2,3];
(myArray.constructor == Array); // true

So, that works well enough for most needs. That said...

Caveats

Will not work AT ALL in many cases

This pattern, though broken, is quite common:

function Thingy() {
}
Thingy.prototype = {
method1: function() {
},
method2: function() {
}
};

Objects constructed via new Thingy will have a constructor property that points to Object, not Thingy. So we fall right at the outset; you simply cannot trust constructor in a codebase that you don't control.

Multiple Inheritance

An example where it isn't as obvious is using multiple inheritance:

function a() { this.foo = 1;}
function b() { this.bar = 2; }
b.prototype = new a(); // b inherits from a

Things now don't work as you might expect them to:

var f = new b(); // instantiate a new object with the b constructor
(f.constructor == b); // false
(f.constructor == a); // true

So, you might get unexpected results if the object your testing has a different object set as its prototype. There are ways around this outside the scope of this discussion.

There are other uses for the constructor property, some of them interesting, others not so much; for now we will not delve into those uses since it isn't relevant to this discussion.

Will not work cross-frame and cross-window

Using .constructor for type checking will break when you want to check the type of objects coming from different window objects, say that of an iframe or a popup window. This is because there's a different version of each core type constructor in each `window', i.e.

iframe.contentWindow.Array === Array // false


Using the instanceof operator...

The instanceof operator is a clean way of testing object type as well, but has its own potential issues, just like the constructor property.

var myArray = [1,2,3];
(myArray instanceof Array); // true
(myArray instanceof Object); // true

But instanceof fails to work for literal values (because literals are not Objects)

3 instanceof Number // false
'abc' instanceof String // false
true instanceof Boolean // false

The literals need to be wrapped in an Object in order for instanceof to work, for example

new Number(3) instanceof Number // true

The .constructor check works fine for literals because the . method invocation implicitly wraps the literals in their respective object type

3..constructor === Number // true
'abc'.constructor === String // true
true.constructor === Boolean // true

Why two dots for the 3? Because Javascript interprets the first dot as a decimal point ;)

Will not work cross-frame and cross-window

instanceof also will not work across different windows, for the same reason as the constructor property check.



Using the name property of the constructor property...

Does not work AT ALL in many cases

Again, see above; it's quite common for constructor to be utterly and completely wrong and useless.

Does NOT work in <IE9

Using myObjectInstance.constructor.name will give you a string containing the name of the constructor function used, but is subject to the caveats about the constructor property that were mentioned earlier.

For IE9 and above, you can monkey-patch in support:

if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
Object.defineProperty(Function.prototype, 'name', {
get: function() {
var funcNameRegex = /function\s+([^\s(]+)\s*\(/;
var results = (funcNameRegex).exec((this).toString());
return (results && results.length > 1) ? results[1] : "";
},
set: function(value) {}
});
}

Updated version from the article in question. This was added 3 months after the article was published, this is the recommended version to use by the article's author Matthew Scharley. This change was inspired by comments pointing out potential pitfalls in the previous code.

if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
Object.defineProperty(Function.prototype, 'name', {
get: function() {
var funcNameRegex = /function\s([^(]{1,})\(/;
var results = (funcNameRegex).exec((this).toString());
return (results && results.length > 1) ? results[1].trim() : "";
},
set: function(value) {}
});
}


Using Object.prototype.toString

It turns out, as this post details, you can use Object.prototype.toString - the low level and generic implementation of toString - to get the type for all built-in types

Object.prototype.toString.call('abc') // [object String]
Object.prototype.toString.call(/abc/) // [object RegExp]
Object.prototype.toString.call([1,2,3]) // [object Array]

One could write a short helper function such as

function type(obj){
return Object.prototype.toString.call(obj).slice(8, -1);
}

to remove the cruft and get at just the type name

type('abc') // String

However, it will return Object for all user-defined types.



Caveats for all...

All of these are subject to one potential problem, and that is the question of how the object in question was constructed. Here are various ways of building objects and the values that the different methods of type checking will return:

// using a named function:
function Foo() { this.a = 1; }
var obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // true
(obj.constructor.name == "Foo"); // true

// let's add some prototypical inheritance
function Bar() { this.b = 2; }
Foo.prototype = new Bar();
obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // false
(obj.constructor.name == "Foo"); // false

// using an anonymous function:
obj = new (function() { this.a = 1; })();
(obj instanceof Object); // true
(obj.constructor == obj.constructor); // true
(obj.constructor.name == ""); // true

// using an anonymous function assigned to a variable
var Foo = function() { this.a = 1; };
obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // true
(obj.constructor.name == ""); // true

// using object literal syntax
obj = { foo : 1 };
(obj instanceof Object); // true
(obj.constructor == Object); // true
(obj.constructor.name == "Object"); // true

While not all permutations are present in this set of examples, hopefully there are enough to provide you with an idea about how messy things might get depending on your needs. Don't assume anything, if you don't understand exactly what you are after, you may end up with code breaking where you don't expect it to because of a lack of grokking the subtleties.

NOTE:

Discussion of the typeof operator may appear to be a glaring omission, but it really isn't useful in helping to identify whether an object is a given type, since it is very simplistic. Understanding where typeof is useful is important, but I don't currently feel that it is terribly relevant to this discussion. My mind is open to change though. :)

Get name of object or class

Get your object's constructor function and then inspect its name property.

myObj.constructor.name

Returns "myClass".

Get name of an object type in Javascript

You can use typeof or instanceof.

For more info, you can check this more detailed answer : How to get a JavaScript object's class?

How to get a JavaScript object's class?

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.

Determine the type of an object?

There are two built-in functions that help you identify the type of an object. You can use type() if you need the exact type of an object, and isinstance() to check an object’s type against something. Usually, you want to use isinstance() most of the times since it is very robust and also supports type inheritance.


To get the actual type of an object, you use the built-in type() function. Passing an object as the only parameter will return the type object of that object:

>>> type([]) is list
True
>>> type({}) is dict
True
>>> type('') is str
True
>>> type(0) is int
True

This of course also works for custom types:

>>> class Test1 (object):
pass
>>> class Test2 (Test1):
pass
>>> a = Test1()
>>> b = Test2()
>>> type(a) is Test1
True
>>> type(b) is Test2
True

Note that type() will only return the immediate type of the object, but won’t be able to tell you about type inheritance.

>>> type(b) is Test1
False

To cover that, you should use the isinstance function. This of course also works for built-in types:

>>> isinstance(b, Test1)
True
>>> isinstance(b, Test2)
True
>>> isinstance(a, Test1)
True
>>> isinstance(a, Test2)
False
>>> isinstance([], list)
True
>>> isinstance({}, dict)
True

isinstance() is usually the preferred way to ensure the type of an object because it will also accept derived types. So unless you actually need the type object (for whatever reason), using isinstance() is preferred over type().

The second parameter of isinstance() also accepts a tuple of types, so it’s possible to check for multiple types at once. isinstance will then return true, if the object is of any of those types:

>>> isinstance([], (tuple, list, set))
True

How to get the Full Type Name of an object

GetType() returns only 1 level when GetType().FullName gives you the entire mapping including the assembly.

Dim objTemp As System.Int32

Debug.Print(objTemp.GetType().FullName)

Getting the object's property name

Use Object.keys():

var myObject = { a: 'c', b: 'a', c: 'b' };

var keyNames = Object.keys(myObject);

console.log(keyNames); // Outputs ["a","b","c"]

Get the instance name of the object no the object type name in C# 4.0

No, this is not possible. Why? Because myCar is only a name for your Car instance inside the scope which you set up the variable for. What gets saved to target.Model is a reference to the Car instance. So, after your sample code, both myCar and target.Model reference the same instance of Car, just with different names. The names themselves are rather unimportant to the execution of the program, it's just a trick we use to make talking about instances easier.

Get an object's class name at runtime

Simple answer :

class MyClass {}

const instance = new MyClass();

console.log(instance.constructor.name); // MyClass
console.log(MyClass.name); // MyClass

However: beware that the name will likely be different when using minified code.

Get the name of a Dart class as a Type or String

The class type can be used as a Type:

Type myType = MyClass;


Related Topics



Leave a reply



Submit