简体   繁体   English

Javascript:当它包含一个点时获取构造函数名称

[英]Javascript: get constructor name when it contains a dot

When I run the following code in the console:当我在控制台中运行以下代码时:

let Func1 = function () {};
let f1 = new Func1();

let Namespace = {};
Namespace.Func2 = function (a, b) {};
let f2 = new Namespace.Func2();

console.log(f1.constructor.name);
console.log(f2.constructor.name);

I get the following output:我得到以下 output:

Func1.      --> as expected
            --> empty string!

I was almost going to give up, but then I realised that, when typing just f1 and f2 in the console, this is the output:我几乎要放弃了,但后来我意识到,在控制台中只输入f1f2时,这就是 output:

> f1
  Func1 {}
> f2
  Namespace.Func2 {}

How does the console know that f2 is an instance of Namespace.Func2 ?控制台如何知道f2Namespace.Func2的一个实例?

So, there has to be a way of getting the constructor name as a string, given the instance object.因此,在给定实例 object 的情况下,必须有一种将构造函数名称作为字符串获取的方法。 Can anyone shed some light on this?任何人都可以对此有所了解吗?


You can run f2 instanceof Namespace.Func2 and it will return true, but I don't want to think that the console loops through every possible class.您可以运行f2 instanceof Namespace.Func2 ,它会返回 true,但我不想认为控制台会循环遍历所有可能的 class。

There is a way to "alias" the constructor name: Namespace.Func3 = function Func_Alias () {};有一种“别名”构造函数名称的方法: Namespace.Func3 = function Func_Alias () {}; , but that's not what I want. ,但这不是我想要的。 I want to retrieve the original name, as shown in the console.我想取回原来的名字,如控制台所示。

I am using Chrome.我正在使用 Chrome。 In Firefox you don't get the name of either function in the console.在 Firefox 中,您不会在控制台中获得 function 的名称。

I think this is the specific behaviour defined as part of the javascript interpreter when dealing with assignation in variable declaration of an anonymous function definition.我认为这是在处理匿名 function 定义的变量声明中的赋值时定义为 javascript 解释器的一部分的特定行为。

let f1 = function(){}

Notice that if it doesn't happen if it is not an anonymous function.请注意,如果不是匿名 function,则不会发生这种情况。 Or if you assigned a variable that contains already a reference to a funcion.或者,如果您分配的变量已经包含对函数的引用。

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

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