假如你老闆叫你作一件事(doWork
)。ide
你說:能夠,可是我須要一些工具(tool1
, tool2
)。函數
老闆:你要的工具我後面會提供給你,如今你立刻寫個計劃。工具
而後,你就能夠這樣寫:this
function doWork(tool1, tool2){ // 如今你有可用的 `tool1, 2` 啦 // 好比,它們可能都是函數: tool1(); tool2(); console.log('Completed!'); }
可是如今你還不能開始作事(doWork()
),由於你都沒有 tool1
和 tool2
. 你須要老闆爲你提供這些工具,老闆是這樣的:code
const boss = { tool1: function(){console.log('Using Tool 1...');}, tool2: function(){console.log('Using Tool 2...');}, provide: function(doWork){ return () => doWork(this.tool1, this.tool2); } }
如今,萬事俱備:it
// 注入依賴: const doWorkWithTools = boss.provide(doWork); // 如今你的 `doWork` 已經擁有 `tool1, 2` 啦: doWorkWithTools();
依賴注入的模式都是相似這樣的,就是定義一個函數實現你的功能,把你所須要的依賴定義成這個函數的參數。io