Javascript技术栈中的四种依赖注入详解


Posted in Javascript onFebruary 23, 2016

作为面向对象编程中实现控制反转(Inversion of Control,下文称IoC)最常见的技术手段之一,依赖注入(Dependency Injection,下文称DI)可谓在OOP编程中大行其道经久不衰。比如在J2EE中,就有大名鼎鼎的执牛耳者Spring。Javascript社区中自然也不乏一些积极的尝试,广为人知的AngularJS很大程度上就是基于DI实现的。遗憾的是,作为一款缺少反射机制、不支持Annotation语法的动态语言,Javascript长期以来都没有属于自己的Spring框架。当然,伴随着ECMAScript草案进入快速迭代期的春风,Javascript社区中的各种方言、框架可谓群雄并起,方兴未艾。可以预见到,优秀的JavascriptDI框架的出现只是早晚的事。

本文总结了Javascript中常见的依赖注入方式,并以inversify.js为例,文章分为四节:

一. 基于Injector、Cache和函数参数名的依赖注入
二. AngularJS中基于双Injector的依赖注入
三. TypeScript中基于装饰器和反射的依赖注入
四. inversify.js——Javascript技术栈中的IoC容器

一. 基于Injector、Cache和函数参数名的依赖注入

尽管Javascript中不原生支持反射(Reflection)语法,但是Function.prototype上的toString方法却为我们另辟蹊径,使得在运行时窥探某个函数的内部构造成为可能:toString方法会以字符串的形式返回包含function关键字在内的整个函数定义。从这个完整的函数定义出发,我们可以利用正则表达式提取出该函数所需要的参数,从而在某种程度上得知该函数的运行依赖。
比如Student类上write方法的函数签名write(notebook, pencil)就说明它的执行依赖于notebook和pencil对象。因此,我们可以首先把notebook和pencil对象存放到某个cache中,再通过injector(注入器、注射器)向write方法提供它所需要的依赖:

var cache = {};
// 通过解析Function.prototype.toString()取得参数名
function getParamNames(func) {
 var paramNames = func.toString().match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1];
 paramNames = paramNames.replace(/ /g, '');
 paramNames = paramNames.split(',');
 return paramNames;
}
var injector = {
 // 将func作用域中的this关键字绑定到bind对象上,bind对象可以为空
 resolve: function (func, bind) {
  // 取得参数名
  var paramNames = getParamNames(func);
  var params = [];
  for (var i = 0; i < paramNames.length; i++) {
   // 通过参数名在cache中取出相应的依赖
   params.push(cache[paramNames[i]]);
  }
  // 注入依赖并执行函数
  func.apply(bind, params);
 }
};
 
function Notebook() {}
Notebook.prototype.printName = function () {
 console.log('this is a notebook');
};
 
function Pencil() {}
Pencil.prototype.printName = function () {
 console.log('this is a pencil');
};
 
function Student() {}
Student.prototype.write = function (notebook, pencil) {
 if (!notebook || !pencil) {
  throw new Error('Dependencies not provided!');
 }
 console.log('writing...');
};
// 提供notebook依赖
cache['notebook'] = new Notebook();
// 提供pencil依赖
cache['pencil'] = new Pencil();
var student = new Student();
injector.resolve(student.write, student); // writing...

有时候为了保证良好的封装性,也不一定要把cache对象暴露给外界作用域,更多的时候是以闭包变量或者私有属性的形式存在的:

function Injector() {
 this._cache = {};
}
 
Injector.prototype.put = function (name, obj) {
 this._cache[name] = obj;
};
 
Injector.prototype.getParamNames = function (func) {
 var paramNames = func.toString().match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1];
 paramNames = paramNames.replace(/ /g, '');
 paramNames = paramNames.split(',');
 return paramNames;
};
 
Injector.prototype.resolve = function (func, bind) {
 var self = this;
 var paramNames = self.getParamNames(func);
 var params = paramNames.map(function (name) {
  return self._cache[name];
 });
 func.apply(bind, params);
};
 
var injector = new Injector();
 
var student = new Student();
injector.put('notebook', new Notebook());
injector.put('pencil', new Pencil())
injector.resolve(student.write, student); // writing...
比如现在要执行Student类上的另一个方法function draw(notebook, pencil, eraser),因为injector的cache中已经有了notebook和pencil对象,我们只需要将额外的eraser也存放到cache中:
function Eraser() {}
Eraser.prototype.printName = function () {
 console.log('this is an eraser');
};
 
// 为Student增加draw方法
Student.prototype.draw = function (notebook, pencil, eraser) {
 if (!notebook || !pencil || !eraser) {
  throw new Error('Dependencies not provided!');
 }
 console.log('drawing...');
};
 
injector.put('eraser', new Eraser());
injector.resolve(student.draw, student);

通过依赖注入,函数的执行和其所依赖对象的创建逻辑就被解耦开来了。
当然,随着grunt/gulp/fis等前端工程化工具的普及,越来越多的项目在上线之前都经过了代码混淆(uglify),因而通过参数名去判断依赖并不总是可靠,有时候也会通过为function添加额外属性的方式来明确地说明其依赖:

Student.prototype.write.depends = ['notebook', 'pencil'];
Student.prototype.draw.depends = ['notebook', 'pencil', 'eraser'];
Injector.prototype.resolve = function (func, bind) {
 var self = this;
 // 首先检查func上是否有depends属性,如果没有,再用正则表达式解析
 func.depends = func.depends || self.getParamNames(func);
 var params = func.depends.map(function (name) {
  return self._cache[name];
 });
 func.apply(bind, params);
};
var student = new Student();
injector.resolve(student.write, student); // writing...
injector.resolve(student.draw, student); // draw...

二. AngularJS中基于双Injector的依赖注入

熟悉AngularJS的同学很快就能联想到,在injector注入之前,我们在定义module时还可以调用config方法来配置随后会被注入的对象。典型的例子就是在使用路由时对$routeProvider的配置。也就是说,不同于上一小节中直接将现成对象(比如new Notebook())存入cache的做法,AngularJS中的依赖注入应该还有一个"实例化"或者"调用工厂方法"的过程。
这就是providerInjector、instanceInjector以及他们各自所拥有的providerCache和instanceCache的由来。
在AngularJS中,我们能够通过依赖注入获取到的injector通常是instanceInjector,而providerInjector则是以闭包中变量的形式存在的。每当我们需要AngularJS提供依赖注入服务时,比如想要获取notebook,instanceInjector会首先查询instanceCache上是存在notebook属性,如果存在,则直接注入;如果不存在,则将这个任务转交给providerInjector;providerInjector会将"Provider"字符串拼接到"notebook"字符串的后面,组成一个新的键名"notebookProvider",再到providerCache中查询是否有notebookProvider这个属性,如有没有,则抛出异常Unknown Provider异常:

Javascript技术栈中的四种依赖注入详解

如果有,则将这个provider返回给instanceInjector;instanceInjector拿到notebookProvider后,会调用notebookProvider上的工厂方法$get,获取返回值notebook对象,将该对象放到instanceCache中以备将来使用,同时也注入到一开始声明这个依赖的函数中。过程描述起来比较复杂,可以通过下面的图示来说明:

 Javascript技术栈中的四种依赖注入详解

需要注意的是,AngularJS中的依赖注入方式也是有缺陷的:利用一个instanceInjector单例服务全局的副作用就是无法单独跟踪和控制某一条依赖链条,即使在没有交叉依赖的情况下,不同module中的同名provider也会产生覆盖,这里就不详细展开了。

另外,对于习惯于Java和C#等语言中高级IoC容器的同学来说,看到这里可能觉得有些别扭,毕竟在OOP中,我们通常不会将依赖以参数的形式传递给方法,而是作为属性通过constructor或者setters传递给实例,以实现封装。的确如此,一、二节中的依赖注入方式没有体现出足够的面向对象特性,毕竟这种方式在Javascript已经存在多年了,甚至都不需要ES5的语法支持。希望了解Javascript社区中最近一两年关于依赖注入的研究和成果的同学,可以继续往下阅读。

 

 三. TypeScript中基于装饰器和反射的依赖注入

笔者本身对于Javascript的各种方言的学习并不是特别热情,尤其是现在EMCAScript提案、草案更新很快,很多时候借助于polyfill和babel的各种preset就能满足需求了。但是TypeScript是一个例外(当然现在Decorator也已经是提案了,虽然阶段还比较早,但是确实已经有polyfill可以使用)。上文提到,Javascript社区中迟迟没有出现一款优秀的IoC容器和自身的语言特性有关,那就依赖注入这个话题而言,TypeScript给我们带来了什么不同呢?至少有下面这几点:
* TypeScript增加了编译时类型检查,使Javascript具备了一定的静态语言特性
* TypeScript支持装饰器(Decorator)语法,和传统的注解(Annotation)颇为相似
* TypeScript支持元信息(Metadata)反射,不再需要调用Function.prototype.toString方法
下面我们就尝试利用TypeScript带来的新语法来规范和简化依赖注入。这次我们不再向函数或方法中注入依赖了,而是向类的构造函数中注入。
TypeScript支持对类、方法、属性和函数参数进行装饰,这里需要用到的是对类的装饰。继续上面小节中用到的例子,利用TypeScript对代码进行一些重构:

class Pencil {
 public printName() {
  console.log('this is a pencil');
 }
}
 
class Eraser {
 public printName() {
  console.log('this is an eraser');
 }
}
 
class Notebook {
 public printName() {
  console.log('this is a notebook');
 }
}
 
class Student {
 pencil: Pencil;
 eraser: Eraser;
 notebook: Notebook;
 public constructor(notebook: Notebook, pencil: Pencil, eraser: Eraser) {
  this.notebook = notebook;
  this.pencil = pencil;
  this.eraser = eraser;
 }
 public write() {
  if (!this.notebook || !this.pencil) {
   throw new Error('Dependencies not provided!');
  }
  console.log('writing...');
 }
 public draw() {
  if (!this.notebook || !this.pencil || !this.eraser) {
   throw new Error('Dependencies not provided!');
  }
  console.log('drawing...');
 }
}

下面是injector和装饰器Inject的实现。injector的resolve方法在接收到传入的构造函数时,会通过name属性取出该构造函数的名字,比如class Student,它的name属性就是字符串"Student"。再将Student作为key,到dependenciesMap中去取出Student的依赖,至于dependenciesMap中是何时存入的依赖关系,这是装饰器Inject的逻辑,后面会谈到。Student的依赖取出后,由于这些依赖已经是构造函数的引用而非简单的字符串了(比如Notebook、Pencil的构造函数),因此直接使用new语句即可获取这些对象。获取到Student类所依赖的对象之后,如何把这些依赖作为构造函数的参数传入到Student中呢?最简单的莫过于ES6的spread操作符。在不能使用ES6的环境下,我们也可以通过伪造一个构造函数来完成上述逻辑。注意为了使instanceof操作符不失效,这个伪造的构造函数的prototype属性应该指向原构造函数的prototype属性。

var dependenciesMap = {};
var injector = {
 resolve: function (constructor) {
  var dependencies = dependenciesMap[constructor.name];
  dependencies = dependencies.map(function (dependency) {
   return new dependency();
  });
  // 如果可以使用ES6的语法,下面的代码可以合并为一行:
  // return new constructor(...dependencies);
  var mockConstructor: any = function () {
   constructor.apply(this, dependencies);
  };
  mockConstructor.prototype = constructor.prototype;
  return new mockConstructor();
 }
};
function Inject(...dependencies) {
 return function (constructor) {
  dependenciesMap[constructor.name] = dependencies;
  return constructor;
 };
}

injector和装饰器Inject的逻辑完成后,就可以用来装饰class Student并享受依赖注入带来的乐趣了:

// 装饰器的使用非常简单,只需要在类定义的上方添加一行代码
// Inject是装饰器的名字,后面是function Inject的参数
@Inject(Notebook, Pencil, Eraser)
class Student {
 pencil: Pencil;
 eraser: Eraser;
 notebook: Notebook;
 public constructor(notebook: Notebook, pencil: Pencil, eraser: Eraser) {
  this.notebook = notebook;
  this.pencil = pencil;
  this.eraser = eraser;
 }
 public write() {
  if (!this.notebook || !this.pencil) {
   throw new Error('Dependencies not provided!');
  }
  console.log('writing...');
 }
 public draw() {
  if (!this.notebook || !this.pencil || !this.eraser) {
   throw new Error('Dependencies not provided!');
  }
  console.log('drawing...');
 }
}
var student = injector.resolve(Student);
console.log(student instanceof Student); // true
student.notebook.printName(); // this is a notebook
student.pencil.printName(); // this is a pencil
student.eraser.printName(); // this is an eraser
student.draw(); // drawing
student.write(); // writing

利用装饰器,我们还可以实现一种比较激进的依赖注入,下文称之为RadicalInject。RadicalInject对原代码的侵入性比较强,不一定适合具体的业务,这里也一并介绍一下。要理解RadicalInject,需要对TypeScript装饰器的原理和Array.prototype上的reduce方法理解比较到位。

function RadicalInject(...dependencies){
 var wrappedFunc:any = function (target: any) {
  dependencies = dependencies.map(function (dependency) {
   return new dependency();
  });
  // 使用mockConstructor的原因和上例相同
  function mockConstructor() {
   target.apply(this, dependencies);
  }
  mockConstructor.prototype = target.prototype;
 
  // 为什么需要使用reservedConstructor呢?因为使用RadicalInject对Student方法装饰之后,
  // Student指向的构造函数已经不是一开始我们声明的class Student了,而是这里的返回值,
  // 即reservedConstructor。Student的指向变了并不是一件不能接受的事,但是如果要
  // 保证student instanceof Student如我们所期望的那样工作,这里就应该将
  // reservedConstructor的prototype属性指向原Student的prototype
  function reservedConstructor() {
   return new mockConstructor();
  }
  reservedConstructor.prototype = target.prototype;
  return reservedConstructor;
 }
 return wrappedFunc;
}

使用RadicalInject,原构造函数实质上已经被一个新的函数代理了,使用上也更为简单,甚至都不需要再有injector的实现:

@RadicalInject(Notebook, Pencil, Eraser)
class Student {
 pencil: Pencil;
 eraser: Eraser;
 notebook: Notebook;
 public constructor() {}
 public constructor(notebook: Notebook, pencil: Pencil, eraser: Eraser) {
  this.notebook = notebook;
  this.pencil = pencil;
  this.eraser = eraser;
 }
 public write() {
  if (!this.notebook || !this.pencil) {
   throw new Error('Dependencies not provided!');
  }
  console.log('writing...');
 }
 public draw() {
  if (!this.notebook || !this.pencil || !this.eraser) {
   throw new Error('Dependencies not provided!');
  }
  console.log('drawing...');
 }
}
// 不再出现injector,直接调用构造函数
var student = new Student();
console.log(student instanceof Student); // true
student.notebook.printName(); // this is a notebook
student.pencil.printName(); // this is a pencil
student.eraser.printName(); // this is an eraser
student.draw(); // drawing
student.write(); // writing

由于class Student的constructor方法需要接收三个参数,直接无参调用new Student()会造成TypeScript编译器报错。当然这里只是分享一种思路,大家可以暂时忽略这个错误。有兴趣的同学也可以使用类似的思路尝试代理一个工厂方法,而非直接代理构造函数,以避免这类错误,这里不再展开。

AngularJS2团队为了获得更好的装饰器和反射语法的支持,一度准备另起炉灶,基于AtScript(AtScript中的"A"指的就是Annotation)来进行新框架的开发。但最终却选择拥抱TypeScript,于是便有了微软和谷歌的奇妙组合。

当然,需要说明的是,在缺少相关标准和浏览器厂商支持的情况下,TypeScript在运行时只是纯粹的Javascript,下节中出现的例子会印证这一点。

 

四. inversify.js——Javascript技术栈中的IoC容器

其实从Javascript出现各种支持高级语言特性的方言就可以预见到,IoC容器的出现只是早晚的事情。比如博主今天要介绍的基于TypeScript的inversify.js,就是其中的先行者之一。
inversity.js比上节中博主实现的例子还要进步很多,它最初设计的目的就是为了前端工程师同学们能在Javascript中写出符合SOLID原则的代码,立意可谓非常之高。表现在代码中,就是处处有接口,将"Depend upon Abstractions. Do not depend upon concretions."(依赖于抽象,而非依赖于具体)表现地淋漓尽致。继续使用上面的例子,但是由于inversity.js是面向接口的,上面的代码需要进一步重构:

interface NotebookInterface {
 printName(): void;
}
interface PencilInterface {
 printName(): void;
}
interface EraserInterface {
 printName(): void;
}
interface StudentInterface {
 notebook: NotebookInterface;
 pencil: PencilInterface;
 eraser: EraserInterface;
 write(): void;
 draw(): void;
}
class Notebook implements NotebookInterface {
 public printName() {
  console.log('this is a notebook');
 }
}
class Pencil implements PencilInterface {
 public printName() {
  console.log('this is a pencil');
 }
}
class Eraser implements EraserInterface {
 public printName() {
  console.log('this is an eraser');
 }
}
 
class Student implements StudentInterface {
 notebook: NotebookInterface;
 pencil: PencilInterface;
 eraser: EraserInterface;
 constructor(notebook: NotebookInterface, pencil: PencilInterface, eraser: EraserInterface) {
  this.notebook = notebook;
  this.pencil = pencil;
  this.eraser = eraser;
 }
 write() {
  console.log('writing...');
 }
 draw() {
  console.log('drawing...');
 }
}

由于使用了inversity框架,这次我们就不用自己实现injector和Inject装饰器啦,只需要从inversify模块中引用相关对象:

import { Inject } from "inversify";
 
@Inject("NotebookInterface", "PencilInterface", "EraserInterface")
class Student implements StudentInterface {
 notebook: NotebookInterface;
 pencil: PencilInterface;
 eraser: EraserInterface;
 constructor(notebook: NotebookInterface, pencil: PencilInterface, eraser: EraserInterface) {
  this.notebook = notebook;
  this.pencil = pencil;
  this.eraser = eraser;
 }
 write() {
  console.log('writing...');
 }
 draw() {
  console.log('drawing...');
 }
}

这样就行了吗?还记得上节中提到TypeScript中各种概念只是语法糖吗?不同于上一节中直接将constructor引用传递给Inject的例子,由于inversify.js是面向接口的,而诸如NotebookInterface、PencilInterface之类的接口只是由TypeScript提供的语法糖,在运行时并不存在,因此我们在装饰器中声明依赖时只能使用字符串形式而非引用形式。不过不用担心,inversify.js为我们提供了bind机制,在接口的字符串形式和具体的构造函数之间搭建了桥梁:

import { TypeBinding, Kernel } from "inversify";
 
var kernel = new Kernel();
kernel.bind(new TypeBinding<NotebookInterface>("NotebookInterface", Notebook));
kernel.bind(new TypeBinding<PencilInterface>("PencilInterface", Pencil));
kernel.bind(new TypeBinding<EraserInterface>("EraserInterface", Eraser));
kernel.bind(new TypeBinding<StudentInterface>("StudentInterface", Student));

注意这步需要从inversify模块中引入TypeBinding和Kernel,并且为了保证返回值类型以及整个编译时静态类型检查能够顺利通过,泛型语法也被使用了起来。
说到这里,要理解new TypeBinding<NotebookInterface>("NotebookInterface", Notebook)也就很自然了:为依赖于"NotebookInterface"字符串的类提供Notebook类的实例,返回值向上溯型到NotebookInterface。
完成了这些步骤,使用起来也还算顺手:

var student: StudentInterface = kernel.resolve<StudentInterface>("StudentInterface");
console.log(student instanceof Student); // true
student.notebook.printName(); // this is a notebook
student.pencil.printName(); // this is a pencil
student.eraser.printName(); // this is an eraser
student.draw(); // drawing
student.write(); // writing

以上就是关于Javascript技术栈中的四种依赖注入的全部内容,希望对大家的学习有所帮助。

Javascript 相关文章推荐
用js实现的检测浏览器和系统的函数
Apr 09 Javascript
jQuery easyUI datagrid 增加求和统计行的实现代码
Jun 01 Javascript
JavaScript蒙板(model)功能的简单实现代码
Aug 04 Javascript
深入理解React中es6创建组件this的方法
Aug 29 Javascript
AngularJS轻松实现双击排序的功能
Aug 30 Javascript
浅谈vue的iview列表table render函数设置DOM属性值的方法
Sep 30 Javascript
webpack打包react项目的实现方法
Jun 21 Javascript
js核心基础之闭包的应用实例分析
May 11 Javascript
Vue+element 解决浏览器自动填充记住的账号密码问题
Jun 11 Javascript
Vue组件间数据传递的方式(3种)
Jul 13 Javascript
Vue $attrs &amp; inheritAttr实现button禁用效果案例
Dec 07 Vue.js
Vue页面渲染中key的应用实例教程
Jan 12 Vue.js
JQuery+EasyUI轻松实现步骤条效果
Feb 22 #Javascript
全面解析Bootstrap布局组件应用
Feb 22 #Javascript
基于jQuery实现带动画效果超炫酷的弹出对话框(附源码下载)
Feb 22 #Javascript
JavaScript function函数种类详解
Feb 22 #Javascript
JavaScript+html5 canvas实现图片破碎重组动画特效
Feb 22 #Javascript
jQuery获取字符串中出现最多的数
Feb 22 #Javascript
jQuery基于muipicker实现仿ios时间选择
Feb 22 #Javascript
You might like
php preg_filter执行一个正则表达式搜索和替换
2012/02/27 PHP
如何获知PHP程序占用多少内存(memory_get_usage)
2012/09/23 PHP
PHP中遇到BOM、编码导致json_decode函数无法解析问题
2014/07/02 PHP
PHP框架自动加载类文件原理详解
2017/06/06 PHP
PHP count_chars()函数讲解
2019/02/14 PHP
jquery 图片轮换效果
2010/07/29 Javascript
JavaScript初学者需要了解10个小技巧
2010/08/25 Javascript
深入理解javascript动态插入技术
2013/11/12 Javascript
js和jquery中循环的退出和继续学习记录
2014/09/06 Javascript
javascript的函数作用域
2014/11/12 Javascript
JavaScript正则表达式小结(test|match|search|replace|split|exec)
2016/12/08 Javascript
jQuery动态移除和添加背景图片的方法详解
2017/03/07 Javascript
vue 引入公共css文件的简单方法(推荐)
2018/01/20 Javascript
Vue.js 中的实用工具方法【推荐】
2019/07/04 Javascript
JavaScript cookie原理及使用实例
2020/05/08 Javascript
python基础入门详解(文件输入/输出 内建类型 字典操作使用方法)
2013/12/08 Python
详细解析Python中__init__()方法的高级应用
2015/05/11 Python
python微信公众号之关键词自动回复
2018/06/15 Python
详解python如何在django中为用户模型添加自定义权限
2018/10/15 Python
python Tkinter版学生管理系统
2019/02/20 Python
Python多进程入门、分布式进程数据共享实例详解
2019/06/03 Python
Python实现桌面翻译工具【新手必学】
2020/02/12 Python
TensorBoard 计算图的查看方式
2020/02/15 Python
pyqt5 QlistView列表显示的实现示例
2020/03/24 Python
CSS3制作半透明边框(Facebox)类似渐变
2012/12/09 HTML / CSS
澳大利亚工具仓库:Tools Warehouse
2018/10/15 全球购物
大学辅导员事迹材料
2014/02/05 职场文书
怎样写好自我评价呢?
2014/02/16 职场文书
《天游峰的扫路人》教学反思
2014/04/25 职场文书
大学生党员承诺书
2014/05/20 职场文书
单位委托书
2014/10/15 职场文书
感谢信的格式
2015/01/21 职场文书
世界名著读书笔记
2015/06/25 职场文书
合理化建议书范文
2015/09/14 职场文书
优秀共产党员事迹材料2016
2016/02/29 职场文书
2019年鼓励无偿献血倡议书
2019/09/17 职场文书