Drew Noakes
Drew Noakes

Reputation: 310907

Determine name of a JavaScript object instance's class

Imagine a JavaScript "class" Foo:

var Foo = function()
{
};

And an instance of that class:

var foo = new Foo();

Can I obtain the string Foo directly from the instance foo, or is Foo just a transitive variable that cannot be associated with the instance foo after instantiation?


EDIT 1 SLaks suggests using foo.constructor. This gives:

function ()
{
}

This approach works if the function is defined in the form:

function Foo()
{}

...but this might not always be the case.


EDIT 2 Trying skizeey's approach doesn't work either. It is essentially a more complete attempt as Slack's method, but yields an empty string: ""


EDIT 3 I wonder whether this is actually possible somehow. Notice the following transcript from Chrome's JavaScript console:

> var Foo = function() {}
undefined
> var foo = new Foo();
undefined
> foo
Foo

In the last line, Chrome clearly knows that the object is of type Foo. However this may just be a Chrome thing, and not standard JavaScript or even inaccessible from the language itself.

Upvotes: 2

Views: 1851

Answers (4)

jurassix
jurassix

Reputation: 1509

With named function:

> var Foo = function Foo(){};
> undefined
> var foo = new Foo();
> undefined
> foo.constructor.name
> "Foo"

With unnamed function:

> var Foo = function (){};
> undefined
> var foo = new Foo();
> undefined
> foo.constructor.name
> ""

Upvotes: 4

Mark Reed
Mark Reed

Reputation: 95252

There is no way to achieve what you want without modifying the module code.

When you define a function like

var Foo = function() {...}

The function - and any object created using it as a constructor - has no knowledge of the name Foo. You might as well do var x = 0 and then attempt to get the value 0 to tell you about the name x.

Upvotes: 2

Sal Rahman
Sal Rahman

Reputation: 4748

From another thread:

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

You're essentially just grabbing the entire constructor as a string, and then extracting its name.

One caveat though: like what clentfort said on a comment to SLaks' answer, there's no one stopping anyone from overwriting an object's constructor property.

Another caveat: you are also going to have to explicitly name your function, too.

Upvotes: 0

SLaks
SLaks

Reputation: 887453

You can get the Foo function by from foo.constructor.
However, you cannot associate that function instance with the name of the variable you assign it to.

Upvotes: 0

Related Questions