简体   繁体   English

有没有一种方法来获取函数表达式的构造函数名称?

[英]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? 也许有些骇客?

When you use function expression, var Func = function() {...} . 使用函数表达式时, var Func = function() {...} The function is assigned to the Func variable as an object reference (functions are objects as well). 该函数被分配给Func变量作为对象引用(函数也是对象)。 So, when you use new Func() to instantiate an instance, it is actually something like new (function() {...}) , an amounymous constructor. 因此,当您使用new Func()实例化一个实例时,它实际上就像是一个不祥的构造new (function() {...}) 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. 这在OOP样式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. 这是kangax文章中的一个示例。 Please notice the difference I highlighted. 请注意我强调的区别。

在此处输入图片说明在此处输入图片说明

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. 使用function X() { } ,或者接受您不能为其分配名称的想法。

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() { } . 但这在某些较旧的浏览器(特定版本的IE)中不受支持,并且与仅使用function X() { } 无关

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM