Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the constructor's name in JavaScript?

Assume the following program:

var SomeConstructor = function() { }; var instance = = new SomeConstructor (); 

The expression instance instanceof SomeConstructor yields True, so instance has to know somehow that it was constructed by the function SomeConstructor. Is there way to retrieve the name SomeConstructor directly from instance?

(In my problem at hand, I have a hierarchy of prototypes implementing possible signals in my application. I have to access the type of a signal which shall be equivalent to the constructor used to create that signal.)

like image 864
Marc Avatar asked Oct 11 '10 09:10

Marc


People also ask

What is constructor name in JavaScript?

A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.

How do you find the type of an object?

Get and print the type of an object: type() type() returns the type of an object. You can use this to get and print the type of a variable and a literal like typeof in other programming languages. The return value of type() is type object such as str or int .

What is property name in JavaScript?

The function name property of the javascript object is used to return the name of the function. This name property of the function is only readable and cannot be altered. The name of the function which was given when the function was created is returned by Function.name.

How do you find out what type an object is JavaScript?

Use the typeof operator to get the type of an object or variable in JavaScript. The typeof operator also returns the object type created with the "new" keyword. As you can see in the above example, the typeof operator returns different types for a literal string and a string object.


1 Answers

On Chrome (7.0.544.0 dev), if I do:

function SomeConstructor() { }  var instance = new SomeConstructor();  console.log(instance.constructor.name); 

it prints 'SomeConstructor'...but if SomeConstructor is defined as an unnamed function as you have it, it will print an empty string instead.

If I print instance.constructor it prints the same thing as it does if I print SomeConstructor in the code you have. The instanceof operator need only compare these two values to see that they are equal to be able to return true.

like image 122
sje397 Avatar answered Oct 15 '22 11:10

sje397