2017-12-03 107 views
0

如何從基類本身獲得子類的名稱(即調用基類的構造函數)TypeScript。我有一些代碼設置爲:如何從打字稿中的父類中獲取子類的名稱?

class Animal{ 
    constructor(){ console.log(this.constructor.name)} //this is throwing error} 
} 
class Cow extends Animal{ 
constructor(){ super() } 
} 
new Cow() // this should log "Cow" 

在用於工作,但似乎這架飛機Jsthis.constructor.nameTypeScript的情況。 我得到的錯誤是:

error TS2339: Property 'name' does not exist on type 'Function'. 

請幫忙。謝謝

+0

[對我的作品(http://www.typescriptlang.org/play/#src=class%20Animal%7B%20constructor()%20%7B%20console.log (%22name%22%2C%20this.constructor.name)%3B%20%7D%20%7D%0D%0Aclass%20Cow%20extends%20Animal%7B%20constructor()%7B%20super()%20%7D %2%7D%0D%0Anew%20Cow()),在我刪除了內嵌評論後,「隱藏」了* Animal#constructor()*的結尾'},並添加了一些實際的日誌記錄 – Thomas

+0

hmm!它怎麼不適合我。 – CodeBlooded

+0

此錯誤是編譯錯誤還是運行時錯誤?如果這是一個編譯錯誤,那麼你正在運行什麼打字稿? –

回答

0

這應該失敗的唯一原因是在Internet Explorer/IE Mobile中,因爲Function.name基本支持不存在。在所有其他瀏覽器中,它應該可以工作。

如果您的目標是ESNEXT並且輸出包含ECMAScript類(即與TypeScript類似),則此功能甚至可以工作。下面的代碼可以在快節奏的快樂瀏覽器中工作......並且如果通過TypeScript編譯器運行它,純文本也可以工作(除非如上所述)。

class Animal { 
 
    constructor() { 
 
     console.log(this.constructor.name); 
 
    } 
 
} 
 

 
class Cow extends Animal{ 
 
    constructor() { 
 
     super(); 
 
    } 
 
} 
 

 
new Cow();

+0

這段代碼和我的問題一樣。這不工作!這就是爲什麼我要求幫助.. – CodeBlooded

+0

@CodeBloded - 你使用什麼瀏覽器?我在多個瀏覽器上進行了測試,並注意到那些不適合我的答案。 – Fenton