2017-08-07 3 views
0

の 'this'の1つのクラスで2つのクラスを拡張すると、私は3番目のクラスからどのように拡張されていないのかという問題に遭遇しました..だから、本当にパラメータ 'TYPE' Cで、getType()をクラスCで呼び出すことができます。JavaScriptの

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では、基本的に '延長する'は 'prototypical inheritance'です。ベースオブジェクトはプロトタイプを1つしか持てないため、複数の継承を行うことはできません。 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