2015-06-22 75 views
2

你好,我想實現這樣的場景:打字稿 - 重載私有方法

class A implements InterfaceForA 
{ 
    a():void 
    { 
     this.b(); 
    } 
} 

Class B extends A 
{ 
    private b():void 
    { 
     console.log('Hi'); 
    } 
} 

但它拋出:

錯誤TS2339:房產 'B' 不會在 'A' 型存在。

所以我更新了我的班,現在它拋出:

錯誤TS2415:類 'B' 正確擴展基類 'A'。類型具有私有屬性'b'的單獨聲明。

隨着代碼:

class A implements InterfaceForA 
{ 
    a():void 
    { 
     this.b(); 
    } 

    private b():void 
    { 
     console.log('Hello'); 
    } 
} 

Class B extends A 
{ 
    private b():void 
    { 
     console.log('Hi'); 
    } 
} 

在C++中,我將在類中設置的方法B()作爲虛擬專用,和問題將得到解決。在JS中,它根本不是問題。如何在TypeScript中做到這一點?

回答

6

在C++中,你實際上將它設置爲受保護的。私人成員是私人的。

Typescript> = 1.3支持受保護的限定符。

參見:What is the equivalent of protected in TypeScript?

+0

在C++中, '私人虛擬' 不同於保護。它可以被重寫,但不能從派生類中調用。 –

+0

@AntonPilyak謝謝!很高興知道。 – Andrew