How to find name of name function in javascript constructors?

For example, compare these two:

function Person(name) {
 this.name = name;
}
var john = new Person('John');
console.log(john.constructor);
// outputs: Person(name)

var MyJSLib = {
 Person : function (name) {
   this.name = name;
 }
}
var john2 = new MyJSLib.Person('John');
console.log(john2.constructor);
// outputs: function()

The first form is useful for debugging at runtime. The second form requires additional steps to find out which object you have.

I know that I can write a descriptive function toString or call the toSource method for the constructor to get more information, but I need the easiest way.

Is there any way to do this? Suggestions?

+3
source share
3 answers

Well, this is because you are using an anonymous function.

You can specify the names of anonymous functions (yes, that sounds weird), you could:

var MyJSLib = {
 Person : function Person (name) {
   this.name = name;
 }
}
var john2 = new MyJSLib.Person('John');
console.log(john2.constructor);

, , , , .

, :

console.log(john2.constructor === MyJSLib.Person); // true
+6

, , "instanceof", . ( ),

var MyJSLib = {
 Person : function Person(name) {
   this.name = name;
 }
}
+3

what you want is the name of the owner in the namespace, therefore.

function getName(namespace, obj) {
  for name in namespace:
    if (namespace[name] == obj) return name;
}
console.log(getNameOf(MyJSLib, john2.constructor));
-1
source

Source: https://habr.com/ru/post/1715835/


All Articles