假如你老板叫你作一件事(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