Subtubes
Subtubes

Reputation: 16873

Is there a way to get the constructor name of a function expression?

I noticed in my code that I cannot get the name of the constructor when I use a function expression.

var X = function () { /* some code*/ };
var foo = new X();
console.log(foo.constructor.name); // ""

but if I use a function declaration I can

function X() {/*some code*/}
var foo = new X();
console.log(foo.constructor.name); //"X"

Is there a way to get the name of the constructor when I use a function expression? Perhaps some hack?

Upvotes: 0

Views: 52

Answers (2)

Leo
Leo

Reputation: 13838

When you use function expression, var Func = function() {...}. The function is assigned to the Func variable as an object reference (functions are objects as well). So, when you use new Func() to instantiate an instance, it is actually something like new (function() {...}), an amounymous constructor. There's nothing to do with the variable indicator. That's why you can't get the variable name.

Alternatively, you can use a named function expression, which might be a little bit different though.

var X = function Func() { /* some code*/ };
var foo = new X();
console.log(foo.constructor.name); // "Func"

This is very commonly used in OOP style JS. Another example:

function Obj() {...}
Obj.prototype.method = function _method() { ... };

One of advantages to do so is that, when you debug your code, at break points you could see the function name in call stack, rather than "anounymous". Here's an example from kangax's article. Please notice the difference I highlighted.

enter image description here enter image description here

Upvotes: 2

user229044
user229044

Reputation: 239311

You can't gets its name if you don't name it.

Either use function X() { }, or accept that you can't assign a name to it.

You can freely mix the syntaxes

var Y = function X() { };
(new Y).constructor.name; // "X"

But this isn't supported in some older browsers (specific versions of IE) and has no benefits over simply using function X() { }.

Upvotes: 1

Related Questions