// A.js
class A {
}
export default new A();
// B.js
import C from './C';
class B {
}
export default new B();
// C.js
import A from './A';
import B from './B';
class C {
constructor(A, B){
this.A = A;
this.B = B; // undefined
}
}
export default new C(A, B)
我導入它們是這樣的:
// stores/index.js
import A from './A';
import B from './B';
import C from './C';
export {
A,
B,
C
}
而且從我的應用程序入口點我做的:
import * as stores from './stores';
我(希望)預期執行順序是A - >乙 - > C,但實際上它是A-> C-> B.
這是由於模塊B導入了C,所以C模塊在B模塊之前被評估。這在C的設置中產生問題,因爲在那種情況下,B將是undefined。
我見過類似的question,但我不確定init函數是否是這裏最好的解決方案,這似乎有點不合理。
問題:在ES6中解決這種循環依賴關係的最佳做法是什麼?它可能適用於不同的環境(Babel,Rollup)?
*預期執行的順序是A - >乙 - > C * - 爲其切入點?如果甚至沒有使用C,爲什麼C在B中導入? – estus
它被使用,這是一個缺少實現細節的例子。我已經更新了添加入口點的問題 – Leonardo
省略的細節在這裏改變了一切。不會有循環依賴,因爲未使用的導入被跳過。考慮提供http://stackoverflow.com/help/mcve。同樣僅僅爲單例使用類是反模式。 – estus