jotaelesalinas
jotaelesalinas

Reputation: 1497

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:

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:

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

How does the console know that f2 is an instance of Namespace.Func2?

So, there has to be a way of getting the constructor name as a string, given the instance 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.

There is a way to "alias" the constructor name: 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. In Firefox you don't get the name of either function in the console.

Upvotes: 1

Views: 112

Answers (1)

Jose Marin
Jose Marin

Reputation: 964

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.

let f1 = function(){}

Notice that if it doesn't happen if it is not an anonymous function. Or if you assigned a variable that contains already a reference to a funcion.

Upvotes: 1

Related Questions