2017-10-11 80 views
0

如何在控制器類Main中實例化新類時構建JS代碼。使用參數創建類或分別調用其方法

解決方案:

答:傳遞參數,同時創造新的類 - new Options(args) - 讓Options的構造函數中調用它自己的方法。 B:創建新類並在對象上調用類的方法。

後來我在另一個類中使用Options的屬性。

// A 
class Main { 
constructor(options) { 
    this.options = new Options(options); 

    { firstProperty, secondProperty } = this.options; 
    this.another = new Another(firstProperty, secondProperty); 
    } 
} 

// B 
class Main { 
constructor(options) { 
    this.options = new Options(); 
    const firstProperty = this.options.methodA(options); 
    const secondProperty = this.options.methodB(options); 

    this.another = new Another(); 
    const anotherPropety = this.another.methodA(firstProperty); 
    (...) 
    } 
} 
+0

這兩個代碼似乎並不相同。在B中,您不要將這兩個屬性複製到'this.another'。另外,如果'this.other'是'this.another'? – Barmar

+0

它們是等價的,我應該添加'etc ...'。現在,它只是「另一個」,這是錯誤的,謝謝你發現它。 –

回答

0

出於解耦的目的,我會建議第三個選項。

//main.js 
class Main { 
    constructor(options) { 
    this.options = options; 
    // all instances of class would have: 
    this.options.foo = 'bar' 
    } 

    method() { 
    return `${this.options.foo} - ${this.options.setup}` 
    } 
} 

// example.js 
const options = new Options({setup: 'options'}); 
const example = new Main(options); 
console.log(example.method()); 

這可以讓您將您的依賴注入到給定的類中,這使得爲您的代碼編寫測試變得更加簡單。它也給你帶來的好處(只要你保持一個通用的接口),在之後的某個時間點換出Options,而不必在任何地方找到你可能已經硬編碼到一個類中。

+0

所以'Main'可以訪問'Options'中的所有方法。文件'example.js'現在是一個控制器/調度器。我需要中心對象來初始化新對象,從其他對象中傳遞他們需要的屬性 - 比如你的'example.js'。 –

+0

非常好,這取決於[控制反轉](https://en.wikipedia.org/wiki/Inversion_of_control)和[依賴注入](https://en.wikipedia.org/wiki/Dependency_injection )。實際上,它可以幫助解耦你的代碼片斷,從而使部件更加可以互換,這有助於測試嘲笑以及提高代碼的可重用性和可擴展性。 –

相關問題