javascript 模块化和依赖注入之间的区别

Difference between javascript modularisation and dependency Injection

javascript 代码的模块化(以 browserify 为例)和依赖注入有什么区别?

它们是同义词吗?两人要在一起吗?还是我遗漏了一些要点?

你可以参考这个article:

Modules are code fragments that implement certain functionality and are written by using specific techniques. There is no out-of-the box modularization scheme in the JavaScript language. The upcoming ECMAScript 6 specification tends to resolve this by introducing the module concept in the JavaScript language itself. This is the future.

Dependency injection in JavaScript

The goal

Let's say that we have two modules. The first one is a service which makes Ajax requests and the second one is a router.

var service = function() {
    return { name: 'Service' };
}
var router = function() {
    return { name: 'Router' };
}

We have another function which needs these modules.

var doSomething = function(other) {
    var s = service();
    var r = router();
};

And to make the things a little bit more interesting the function needs to accept one more parameter. Sure, we could use the above code, but that's not really flexible. What if we want to use ServiceXML or ServiceJSON. Or what if we want to mockup some of the modules for testing purposes. We can't just edit the body of the function. The first thing which we all come up with is to pass the dependencies as parameters to the function. I.e.:

var doSomething = function(service, router, other) {
    var s = service();
    var r = router();
};

By doing this we are passing the exact implementation of the module which we want. However this brings a new problem. Imagine if we have doSomething all over our code. What will happen if we need a third dependency. We can't edit all the function's calls. So, we need an instrument which will do that for us. That's what dependency injectors are trying to solve. Let's write down few goals which we want to achieve:

  • we should be able to register dependencies
  • the injector should accept a function and should return a function which somehow gets the needed resources
  • we should not write a lot, we need short and nice syntax
  • the injector should keep the scope of the passed function
  • the passed function should be able to accept custom arguments, not only the described dependencies

A nice list isn't it. Let's dive in.

模块化是指将代码分解成单独的、独立的"packages"。
依赖注入是指不硬编码对其他模块的引用。

作为一个实际的例子,你可以编写不使用依赖注入的模块:

import { Foo } from 'foo';

export function Bar() {
    return Foo.baz();
}

这里有两个 模块,但是这个模块导入了一个特定的其他硬编码模块。

使用依赖注入编写的相同模块:

export function Bar(foo) {
    return foo.baz();
}

然后其他人可以将其用作:

import { Foo } from 'foo';
import { Bar } from 'bar';

Bar(Foo());

在调用时注入 Foo 依赖项,而不是对依赖项进行硬编码。