JS模块加载器如何解决循环依赖问题?

ts2015
  • 461

最近在看NEJ的模块加载器define.js的源码,对其中解决循环依赖的部分没太看懂。
想问下大家,现在各种JS模块加载器对循环依赖问题都是如何解决的?
比如requirejs?

回复
阅读 3.6k
1 个回答

老哥多看api啊 官方api有实现的
Circular Dependencies
§ 1.3.8
If you define a circular dependency ("a" needs "b" and "b" needs "a"), then in this case when "b"'s module function is called, it will get an undefined value for "a". "b" can fetch "a" later after modules have been defined by using the require() method (be sure to specify require as a dependency so the right context is used to look up "a"):
//Inside b.js:
define(["require", "a"],

function(require, a) {
    //"a" in this case will be null if "a" also asked for "b",
    //a circular dependency.
    return function(title) {
        return require("a").doSomething();
    }
}

);
翻一下就是
如果你定义了一个循环依赖(a依赖b,b同时依赖a),则在这种情形下当b的模块函数被调用的时候,它会得到一个undefined的a。b可以在模块已经定义好后用require()方法再获取a(记得将require作为依赖注入进来):
//b.js:
define(["require", "a"],

function(require, a) {
    //"a"将是null,如果a/b间是循环依赖
    return function(title) {
        return require("a").doSomething();
    }
}

);
就是类似于commenjs的依赖就近

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏