[英]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.