2014-03-24 46 views
1

在嘗試瞭解如何遍歷生成的Javascript中的原型鏈之後,我未能在下面的示例中實現WriteInheritedName()功能。這個想法是找到基本類型並寫下它的名字。有任何想法嗎?如何訪問Typescript中的基本類型?

class Animal { 
} 

class Snake extends Animal { 
} 

function WriteClassName(cls) { 
    console.log(cls.name); 
} 

function WriteInheritedName(cls) { 
    console.log("I wish I new how to write Animal"); 
} 

WriteClassName(Snake); 
WriteInheritedName(Snake); 
+0

實際上並沒有實際的使用方式來實現它。如果你想在構造函數或方法中訪問超類,使用'super'。您可以在[playground](http://www.typescriptlang.org/Playground/)的下拉菜單中找到「Simple Inheritance」示例。 –

+0

問題是如何實現一個通用的反射機制,只給出由''''global.A'''引用的對象(函數)。即如何實現'''WriteInheritedName'''函數。假定使用getPrototypeOf(),'''__proto__''或''prototype'''屬性來確定運行時任意對象的繼承鏈。 –

回答

2

自己找到了。

function WriteInheritedName(cls) { 
    console.log(Object.getPrototypeOf(cls.prototype).constructor.name); 
}