2017-03-04 42 views
0

這是事情。我有一個叫做A. 我想這個類來擴展類B.JavaScript - 類擴展條件

class A extends B {} 

但事實上,我想B類擴展C,d或E在特定的條件下一個主類:

class B extends B1 {} 

class B extends B2 {} 

class B extends B3 {} 

所以B類將是一個「假」類,只是爲了檢查一個條件,然後擴展正確的類。 在決賽中,結果會是一樣的:

class A extends B1 {} 

class A extends B2 {} 

class A extends B3 {} 

我知道這是可能在PHP中,抽象類或包裝類例如。 但如何在JavaScript ES6中做到這一點?

感謝

+0

我不知道你要解決什麼問題。爲什麼你需要動態聲明類而不是僅僅選擇使用哪個類? –

+0

我需要動態地執行它,因爲'A類擴展B {}'發生在每個用戶請求,並且'B類擴展? {}'取決於請求類型 –

+0

這不能回答我的問題。動態聲明類和動態選擇類是有區別的。我需要經常做後者,前者從不,因此是一個問題。 –

回答

0

因此JavaScript類實際上不在同一經典的繼承方式與其他語言設置,做你想要什麼,最好的辦法就是設置你正在處理的對象的原型。有幾種方法。

Object.setPrototypeOf(currentObj, newPrototype); 

其中newPrototype是您想要繼承的對象。如果你想學習內部工作,這裏有幾篇很好的文章。

http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/

https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch5.md

+0

像魅力一樣工作!感謝您的鏈接 –

0

怪異,但可能:

class subClassFirst { 
 

 
    report() { 
 
    console.log(`Extended ${this.name} from the first class`); 
 
    } 
 
} 
 

 
class subClassSecond { 
 

 
    report() { 
 
    console.log(`Extended ${this.name} from the second class`); 
 
    } 
 
} 
 

 
class subClassThird { 
 

 
    report() { 
 
    console.log(`Extended ${this.name} from the third class`); 
 
    } 
 
} 
 

 
function classCreator(condition) { 
 
    let sub; 
 
    switch (condition) { 
 
    case 'first': 
 
     sub = subClassFirst; 
 
     break; 
 
    case 'second': 
 
     sub = subClassSecond; 
 
     break; 
 
    case 'third': 
 
     sub = subClassThird; 
 
     break; 
 
    } 
 

 
    return (class extends sub { 
 
    constructor(name) { 
 
     super(); 
 
     this.name = name; 
 
    } 
 
    }); 
 
} 
 

 
let myClass; 
 

 
myClass = classCreator('first'); 
 
let mcf = new myClass('f'); 
 

 
myClass = classCreator('second'); 
 
let mcs = new myClass('s'); 
 

 
myClass = classCreator('third'); 
 
let mct = new myClass('t'); 
 

 
mcf.report(); 
 
mcs.report(); 
 
mct.report();