require.js如何实现循环依赖的?
可否写两个闭包,说明一下其中的原理?
可否写两个闭包,说明一下其中的原理?
解决方案 »
- fusioncharts free 谁用过,谁封装过
- mediaplay网页调用,如何只播放其中的一段
- 求解js代码解释
- 『求教』javascript中关于eval的一个疑问
- 问一个js
- 高分求助:javascript日历显示问题
- 较高难度二进制图片显示问题?
- td的innerText中怎么能写入一个Link
- 关于object与html结合的问题,急,在线等待!
- 求助一个菜鸟级的问题,在线等,有分!!
- 求助Jquery LigerUI ligerAccordion 的一个问题,急!急!急!
- jquery easyui combotree 加载数据 tree出来了 但是显示数据undefined
define("aa",["bb"],function(bb){
return {aa:3}
});
define("bb",["aa"],function(aa){
return {bb:aa.aa}
});
require(["bb"],function(bb){
window.alert(bb.bb);
});
}); 比如上面的代码,在require.js中是完全没有问题的
不知他是怎么实现的
define("Employee", ["exports", "Company"], function(exports, Company) {
function Employee(name) {
this.name = name;
this.company = NEW Company.Company(name + "'s own company");
};
exports. EMPLOYEE = EMPLOYEE;
});
define("Company", ["exports", "Employee"], function(exports, Employee) {
function Company(name) {
this.name = name;
this.employees = [];
};
Company.prototype.addEmployee = function(name) {
var employee = new Employee.Employee(name);
this.employees.push(employee);
employee.company = this;
};
exports.Company = Company;
});用exports来解决这个问题
答非所问,我在上面的示例代码已经说明,不用exports,也能实现循环依赖,是怎么做到的
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的依赖就近