2017-08-07 39 views
0

我遇到了這個問題,我不知道如何從第三個類擴展..所以我真的需要用參數'TYPE'調用A類的方法,extend與C,並能夠與類C調用getType()。任何解決方案?在javascript中的'this'的一個類中擴展2個類

const TYPE = 'TYPE' 
 

 
class A { 
 
    constructor(type) { 
 
     this.type = type; 
 
    } 
 
    
 
    getType() { 
 
     return this.type; 
 
    } 
 
} 
 

 
class B { 
 
constructor(id) { 
 
     this.id = id; 
 
    } 
 
    
 
    getId() { 
 
     return this.id; 
 
    } 
 
} 
 

 
class C extends B { 
 
    constructor(id) { 
 
     super(id); 
 
     
 
     //Here should be a function that should bind the method from class A 
 
    } 
 
} 
 

 
const c = new C(1); 
 
console.log(c.getId()) 
 
console.log(c.getType())

+1

爲什麼不能有'B類擴展A'?或者你真的問過如何從'C'中的'A'和'B'繼承? – Bergi

+0

在javascript中,當你執行'extend'時,基本上你正在做的是'原型繼承'。由於你的基礎對象只能有一個原型,你不能做多重繼承。你可以做的一件事是你的B類可以擴展A類,所以間接地你的C類將會擴展這兩個類。 –

+0

'Object.assign(this,A.prototype)'可以去你的評論的地方。 – 4castle

回答

0

const TYPE = 'TYPE' 
 

 
class A { 
 
    constructor(type) { 
 
     this.type = type; 
 
    } 
 
    
 
    getType() { 
 
     return this.type; 
 
    } 
 
    
 
    extend(extendedClassInstance){ 
 
     extendedClassInstance.type = this.type; 
 
     extendedClassInstance.getType = this.getType.bind(extendedClassInstance) 
 
    } 
 
} 
 

 
class B { 
 
constructor(id) { 
 
     this.id = id; 
 
    } 
 
    
 
    getId() { 
 
     return this.id; 
 
    } 
 
} 
 

 
class C extends B { 
 
    constructor(id) { 
 
     super(id); 
 
     (new A(TYPE)).extend(this) 
 
    } 
 
} 
 

 
const c = new C(1); 
 
console.log(c.getId()) 
 
console.log(c.getType())

+0

請勿使用'.bind(extendedClassInstance)'。 – Bergi

相關問題