Hud*_*Hud 10 javascript circular-dependency commonjs ecmascript-6
这是我经常遇到的一个问题,我希望找到正确的方法来处理它.
所以我有这样的设置:
parent.js:
export default {
x: 1
}
Run Code Online (Sandbox Code Playgroud)
a.js:
import parent from 'parent.js'
export default parent.extend(a, { title: 'a' })
Run Code Online (Sandbox Code Playgroud)
b.js:
import parent from 'parent.js'
export default parent.extend(b, { title: 'b' })
Run Code Online (Sandbox Code Playgroud)
很酷,现在我有了一些孩子.但我决定在parent.js中有一个函数来检查对象是否是a或b的实例.
所以我可能这样做:
parent.js:
import a from 'a'
import b from 'b'
export default {
x: 1,
checkType (obj) {
if (obj instanceof a) {
return 'a'
} else if (obj instanceof b) {
return 'b'
}
}
}
Run Code Online (Sandbox Code Playgroud)
那么现在这是一个循环依赖.有一种优雅的方式来处理这个问题吗?
小智 7
在父类中具有知道子类的逻辑是一种严重的反模式.而是在返回类型的子类中添加方法.例如,在a.js:
import parent from 'parent.js';
export default parent.extend(a, { title: 'a', checkObj() { return 'a'; }});
Run Code Online (Sandbox Code Playgroud)
如果期望的回报checkObj始终是title财产的价值,那么当然只是:
// parent.js
export default {
x: 1,
checkObj() { return this.title; }
}
Run Code Online (Sandbox Code Playgroud)
我不知道到底extend在做什么.我假设它是某种子类化机制.
一般来说,循环导入依赖关系虽然有真正必要的方法来处理它们,但是宇宙试图告诉你构造代码的方式有问题.
如果您能够使用 es6 类,那么您可以利用构造函数中的 super() 调用。我经常会做这样的事情:
父.js
export default class {
constructor(options, child) {
this.child = child;
this.x = 1;
}
checkType() {
return this.child;
}
}
Run Code Online (Sandbox Code Playgroud)
A.js
import Parent from './Parent';
export default class extends Parent {
constructor(options) {
super(options, 'a');
}
}
Run Code Online (Sandbox Code Playgroud)
B.js
import Parent from './Parent';
export default class extends Parent {
constructor(options) {
super(options, 'b');
}
}
Run Code Online (Sandbox Code Playgroud)
如果你不想使用类,也许想要更多 FP 风格。你可以让父函数成为一个函数:
父.js
export default function(child) {
return {
x: 1,
checkType (obj) {
return child;
}
extend (something) {
// assuming the returns something as you said
}
}
}
Run Code Online (Sandbox Code Playgroud)
a.js
import parent from 'parent.js'
export default parent('a').extend(a, { title: 'a' })
Run Code Online (Sandbox Code Playgroud)
b.js
import parent from 'parent.js'
export default parent('b').extend(b, { title: 'b' })
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2962 次 |
| 最近记录: |