什么是依赖注入?你可能天天都在用
文章目录
假如你老板叫你做一件事(doWork)。
你说:可以,但是我需要一些工具(tool1, tool2)。
老板:你要的工具我后面会提供给你,现在你马上写个计划。
然后,你就可以这样写:
function doWork(tool1, tool2){
// 现在你有可用的 `tool1, 2` 啦
// 比如,它们可能都是函数:
tool1();
tool2();
console.log('Completed!');
}
但是现在你还不能开始做事(doWork()),因为你都没有 tool1 和 tool2. 你需要老板为你提供这些工具,老板是这样的:
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);
}
}
现在,万事俱备:
// 注入依赖:
const doWorkWithTools = boss.provide(doWork);
// 现在你的 `doWork` 已经拥有 `tool1, 2` 啦:
doWorkWithTools();
依赖注入的模式都是类似这样的,就是定义一个函数实现你的功能,把你所需要的依赖定义成这个函数的参数。

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论