您好,登錄后才能下訂單哦!
這篇文章主要講解了javascript模塊依賴管理的用法,內(nèi)容清晰明了,對此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。
模塊模式定義
模塊是'javascript'的一種設(shè)計(jì)模式,它為函數(shù)定義一個(gè)包裝函數(shù),并且該包裝函數(shù)的返回值與模塊的API保持一致:
function createModule() { function hello(name) { console.log(name + '帥哥你好!'); } return { hello: hello } } // 這里調(diào)用 createModule 來創(chuàng)建一個(gè)模塊實(shí)例 var foo = createModule(); foo.hello('fayin');
單例模塊模式
仔細(xì)研究上面的模塊,我們發(fā)現(xiàn)每次調(diào)用 createModule 都會(huì)生成一個(gè)實(shí)例,很浪費(fèi)。于是我們簡單的包裝一下,就有了單例模塊模式:
var myModule = (function createModule() { function hello(name) { console.log(name + '帥哥你好!'); } return { hello: hello } })() // 調(diào)用方式 myModule.hello('fayin')
模塊依賴管理
現(xiàn)代大多數(shù)模塊依賴管理器本質(zhì)上都是將這種模塊定義封裝進(jìn)一個(gè)友好的API。其核心的方法可以通過下面的例子一窺究竟:
// 通過模塊的單例模式來保存定義的方法 var MyModules = (function() { var modules = {}; function define(name, deps, impl) { console.log(deps.length) for(var i = 0, len = deps.length; i < len; i++) { // deps[i] 看做是函數(shù)名 // modules[deps[i]] 是保存在 modules 對象上的一個(gè)屬性為 deps[i] 的方法 // 每次遍歷將對應(yīng)的方法綁定到函數(shù)名上 deps[i] = modules[deps[i]] } // 在modules 對象上保存方法,其函數(shù)名為 name // 如函數(shù) bar ,impl 為 bar 的函數(shù)體 modules[name] = impl.apply(null, deps); console.log( modules) } function get(name) { return modules[name] } return { define: define, get: get }; })(); // 這里定義一個(gè)函數(shù) bar,返回一個(gè)對象 MyModules.define('bar', [], function() { function hello(who) { return 'Let me introduce: ' + who; } return { hello: hello } }) MyModules.define('foo', ['bar'], function(bar) { var hungry = 'hippo'; function awesome() { return bar.hello(hungry).toUpperCase() } return { awesome: awesome } }) var bar = MyModules.get('bar') console.log(bar.hello('fay')) var foo = MyModules.get('foo') console.log(foo.awesome())
模塊模式的缺陷
從上面的案例我們知道,這個(gè)模式是基于函數(shù)來實(shí)現(xiàn)的,它的優(yōu)勢這里不在贅述(參考jQuery),而它的缺點(diǎn)也非常的明顯。由于函數(shù)的上下文環(huán)境是在運(yùn)行時(shí)確定的,在編譯期間無法確定它的依賴關(guān)系,在運(yùn)行期間我們可以隨意更改API,這導(dǎo)致基于函數(shù)的模塊模式并不穩(wěn)定。
而相比之下,ES6的模塊API更加的穩(wěn)定......
看完上述內(nèi)容,是不是對javascript模塊依賴管理的用法有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。