繁体   English   中英

在javascript中获取构造函数本身内的原型构造函数的名称

[英]Get the name of a prototype constructor inside the constructor itself in javascript

是否有可能在javascript中获取类本身的类名? 它对我的中间件中动态创建的类的递归很有用。 认为这是一个非常不正确的帖子 - 所以我更好地定义了我想要解决的问题:

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();

你可能正在寻找这个:

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

要使其工作,您必须声明上述函数,而不是使用MyClass = function(){} 然后,使用函数的name属性,利用原型链(查询constructor属性时)。

如果需要直接在构造函数中访问,请使用构造函数引用:

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

这个问题涉及类似的主题,它也可能对你有用: 从Javascript函数引用中获取名称作为String?

如果“class”定义正确,则class对象具有contructor属性,这是对类对象的引用。

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

你可以在控制台中检查A.prototype

console.dir(A.prototype)

命令

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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