Get the name of the prototype constructor inside the constructor in javascript

Is it possible to get the class name inside the class itself in javascript? This would be useful for recursing dynamically generated classes in my middleware. Think that this was very wrong, so I better identify the problem I want to solve:

MyClass = function(){ this.classname = ??? // Here is required and needed to store as a property } MyClass.prototype.log = function(){ alert(this.classname); // The alert should be MyClass } var myClassObj = new MyClass(); myClassObj.log(); 
+4
source share
2 answers

You are probably looking for:

 function MyClass() {}; var myInstance = new MyClass(); console.log(myInstance.constructor.name === "MyClass"); // true 

For this to work, you must declare a function as above, and not use MyClass = function(){} . Then the name property of the function is used, using the prototype chain (when querying the constructor property).

If you need to access directly in the constructor, use the link to the constructor:

 function MyClass() { console.log(this.constructor.name === "MyClass"); }; var myInstance = new MyClass(); // true 

This question relates to a similar topic, it may be useful for you too: Get name as String from Javascript function reference?

+3
source

If the "class" is defined correctly, the class object has the contructor property, which is a reference to the class object.

 function A() { alert(this instanceof this.constructor); } var a = new A(); 

you can check A.prototype in console on

 console.dir(A.prototype) 

Command

+1
source

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


All Articles