[英]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? 是否有可能在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(){}
. 要使其工作,您必须声明上述函数,而不是使用
MyClass = function(){}
。 Then, name
property of function is used, leveraging prototype chain (when querying constructor
property). 然后,使用函数的
name
属性,利用原型链(查询constructor
属性时)。
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? 这个问题涉及类似的主题,它也可能对你有用: 从Javascript函数引用中获取名称作为String?
If "class" defined properly, class object has contructor property, which is a reference to class object. 如果“class”定义正确,则class对象具有contructor属性,这是对类对象的引用。
function A() {
alert(this instanceof this.constructor);
}
var a = new A();
you can inspect A.prototype in console by 你可以在控制台中检查A.prototype
console.dir(A.prototype)
command 命令
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.