简体   繁体   中英

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

Is it possible to get the name of a class inside the class itself in javascript? It would be useful for recursions on dynamically created classes in my middleware. Think that was an very improperly post — so I better define 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();

You are probably looking for this:

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

To have this working, you must declare the function as above, not using MyClass = function(){} . Then, name property of function is used, leveraging prototype chain (when querying constructor property).

If you need to access directly in the constructor, use the constructor reference as well:

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

This question deals with similar topic, it might be useful for you as well: Get name as String from a Javascript function reference?

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

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

you can inspect A.prototype in console by

console.dir(A.prototype)

command

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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