views:

40

answers:

3

Assume the following program:

var C = function() { };
x = new C();

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

(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.)

+1  A: 

No. You can use x.constructor to get a direct reference to C, but it's an anonymous function so there's no way of getting its name.

If it were defined like so:

function C() { };
x = new C();

Then it would be possible to use x.constructor.toString() and parse out the name of the function from the returned string. Some browsers would also support x.constructor.name[1].

[1] https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/name

Andy E
+1  A: 

On Chrome (7.0.544.0 dev), if I do:

function C() { }

var x = new C();

console.log(x.constructor.name);

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

If I print x.constructor it prints the same thing as it does if I print C 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.

sje397
I thought I would need a name string of the constructor in order to use the constructor as an index of an array. However, if it is possible to use `x.constructor` directly as an array index, I will be fine.
Marc
@Marc - the closest thing to an 'associative array' in javascript is an object. Javascript arrays are indexed using integers. If you use `x.constructor` as an object's property name (e.g. `map[x.constructor]`) then the constructor property's `toString` method is implicitly called.
sje397
@sje397: Thanks! I mainly program in Python so your explanations how JavaScript does things helped me a lot. I checked the x.constructor.toString() method in the stand-alone Rhino interpreter and it gives me back the source code of the anonymous constructor.
Marc
A: 

This code of yours that needs to know the constructor, can it access the constructor function itself? If so, you can just do that instanceof thing.

It seems that you need to know it by name. This sounds dangerous. Someone can create another constructor that happen to have the same name and it will pass (unless that's what you want, of course).

RichN