2013-05-11 104 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

相關問題