目录

依赖注入的 javascript 简易实现

目录
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Injector {
  constructor() {
    this.dependencies = {};
    this.register = (key, value) => {
      this.dependencies[key] = value;
    };
  }
  resolve(...args) {
    let func = null;
    let deps = null;
    let scope = null;
    const self = this;
    // 应对代码压缩的兼容方案
    if (typeof args[0] === "string") {
      func = args[1];
      deps = args[0].replace(/ /g, "").split(",");
      scope = args[2] || {};
    } else {
      // 反射的一种方式
      func = args[0];
      deps = func
        .toString()
        .match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1]
        .replace(/ /g, "")
        .split(",");
      scope = args[1] || {};
    }
    return (...args) => {
      func.apply(
        scope || {},
        deps.map((dep) =>
          self.dependencies[dep] && dep != ""
            ? self.dependencies[dep]
            : args.shift()
        )
      );
    };
  }
}

injector = new Injector();

injector.register("module1", () => {
  console.log("hello");
});
injector.register("module2", () => {
  console.log("world");
});

var doSomething1 = injector.resolve(function (module1, module2, other) {
  module1();
  module2();
  console.log(other);
});
doSomething1("Other");

console.log("--------");

var doSomething2 = injector.resolve("module1,module2,", function (a, b, c) {
  a();
  b();
  console.log(c);
});
doSomething2("Other");

将上面的代码直接扔到控制台可以看到效果。

参考自 Krasimir 的这篇文章 以及 感谢潇湘待雨的 这篇翻译