2013-05-11 40 views
4

是否有可能在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(); 
+1

的Javascript没有课程。 – 2013-05-11 18:20:34

+0

@ alex23:https://github.com/raganwald/homoiconic/blob/master/2013/02/prototypes.md – 2013-05-11 18:28:15

+0

你可以称它为类或不是。 JavaScript没有那个关键字(尽管它是保留的),但是你可以像使用原型的Java类一样获得相同的功能。对于面向对象的人来说,“类”比“与同一个原型对象相关联的对象”要容易得多。 – 2013-05-11 18:31:07

回答

1

如果“类”定义得当,类对象有构造器属性,它是类对象的引用。

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

您可以通过

console.dir(A.prototype) 

命令检查A.prototype控制台

+0

你知道它是如何在上面写的(现在更好)的原型构造函数吗? – Bernhard 2013-05-11 19:41:14

+0

A.call([])''怎么办? – Bergi 2013-05-11 19:50:07

3

你可能在寻找这样的:

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 

这个问题的交易,它可能对您有用,以及: Get name as String from a Javascript function reference?

+3

不要忘记提及这是一个非标准的财产,并不支持任何地方! – Bergi 2013-05-11 19:28:36

+0

@PavelS。我在构造函数/原型上下文中工作,不要这样声明函数。我的情况如何? – Bernhard 2013-05-11 19:38:56

+0

构造器上下文总是指向新创建的对象(除非它被称为没有'new'的通用函数,否则应该永远不会)。如果你在原型中声明了相同的函数,它将以完全相同的方式工作: 'MyClass.prototype.protF = function(){console.log(this.constructor.name); };' – 2013-05-11 19:43:26

相关问题