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.)
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.
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 .
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With