javascript
RequireJS模块化之循环依赖
如果你定義一個(gè)循環(huán)依賴關(guān)系 (a 依賴b 并且 b 依賴 a),那么當(dāng)b的模塊構(gòu)造函數(shù)被調(diào)用的時(shí)候,傳遞給他的a會(huì)是undefined。?但是b可以在a模塊在被引入之后通過(guò)require(‘a(chǎn)’)來(lái)獲取a?(一定要把require作為依賴模塊,RequireJS才會(huì)使用正確的 context 去查找 a):
1 //Inside b.js: 2 define(["require", "a"], 3 function(require, a) { 4 //"a" in this case will be null if a also asked for b, 5 //a circular dependency. 6 return function(title) { 7 return require("a").doSomething(); 8 } 9 } 10 );通常情況下,你不應(yīng)該使用require()的方式來(lái)獲取一個(gè)模塊,而是使用傳遞給模塊構(gòu)造函數(shù)的參數(shù)。循環(huán)依賴很罕見,通常表明,你可能要重新考慮這一設(shè)計(jì)。然而,有時(shí)需要這樣用,在這種情況下,就使用上面那種指定require()的方式吧。
如果你熟悉 CommonJS 模塊的寫法,你也可以使用?exports?創(chuàng)建一個(gè)空對(duì)象來(lái)導(dǎo)出模塊,這樣定義的模塊可以被其他模塊立即使用。即使在循環(huán)依賴中,也可以安全的直接使用。 不過(guò)這只適用于導(dǎo)出的模塊是對(duì)象,而不是一個(gè)函數(shù):
1 //Inside b.js: 2 define(function(require, exports, module) { 3 //If "a" has used exports, then we have a real 4 //object reference here. However, we cannot use 5 //any of a's properties until after b returns a value. 6 var a = require("a"); 7 8 exports.foo = function () { 9 return a.bar(); 10 }; 11 });?
用依賴數(shù)組的話,記得將?'exports'當(dāng)作依賴模塊:
1 //Inside b.js: 2 define(['a', 'exports'], function(a, exports) { 3 //If "a" has used exports, then we have a real 4 //object reference here. However, we cannot use 5 //any of a's properties until after b returns a value. 6 7 exports.foo = function () { 8 return a.bar(); 9 }; 10 });?
轉(zhuǎn)載于:https://www.cnblogs.com/terrylin/p/3347073.html
新人創(chuàng)作打卡挑戰(zhàn)賽發(fā)博客就能抽獎(jiǎng)!定制產(chǎn)品紅包拿不停!總結(jié)
以上是生活随笔為你收集整理的RequireJS模块化之循环依赖的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 递归(1)
- 下一篇: XML DTD用法【转载】