在物件導向程式設計的領域裡,控制反轉(Inversion of Control,簡稱 IoC)是一種廣受推崇的設計理念,而依賴注入(Dependency Injection,簡稱 DI)則是落地這一理念最常見的技術手段。從 Java 世界裡家喻戶曉的 Spring 框架,到前端領域中深度依賴 DI 機制的 AngularJS,這個模式始終散發著強大的生命力。
遺憾的是,JavaScript 作為一門缺乏反射機制、又不原生支援 Annotation 語法的動態語言,長期以來都缺少一套真正屬於自己的成熟 IoC 容器。不過隨著 ECMAScript 標準進入高速迭代階段,各種方言與框架百花齊放,優秀的 JavaScript DI 方案問世也只是時間問題。
本文將系統梳理 JavaScript 中常見的四類依賴注入方式,並以 inversify.js 為例,展現方言社群在這方面的探索成果:
一、基於 Injector、Cache 與函數參數名的依賴注入
二、AngularJS 中基於雙 Injector 的依賴注入
三、TypeScript 中基於裝飾器與反射的依賴注入
四、inversify.js——JavaScript 技術棧中的 IoC 容器
一、基於 Injector、Cache 與函數參數名的依賴注入
雖然 JavaScript 並不原生支援反射,但 Function.prototype 上的 toString 方法卻為我們打開了一扇窗:它會以字串形式返回包含 function 關鍵字在內的完整函數定義。借助正則表達式,我們便能從中解析出函數所需的參數,進而推斷它的執行依賴。
舉例來說,Student 類上的 write 方法簽名為 write(notebook, pencil),這意味著它的執行依賴於 notebook 與 pencil 兩個物件。於是我們可以先把這些物件放進一個 cache,再透過 injector 把對應的依賴注入到方法中:
var cache = {}; // 通過解析 Function.prototype.toString() 取得參數名 function getParamNames(func) { // 正則表達式出自 https://krasimirtsonev.com/blog/article/Dependency-injection-in-JavaScript var paramNames = func.toString().match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1]; paramNames = paramNames.replace(/ /g, ''); paramNames = paramNames.split(','); return paramNames; } var injector = { resolve: function (func, bind) { var paramNames = getParamNames(func); var params = []; for (var i = 0; i < paramNames.length; i++) { 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...'); }; cache['notebook'] = new Notebook(); 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 類上的另一個方法 draw(notebook, pencil, eraser),由於 cache 中已備有 notebook 與 pencil,我們只需再補上 eraser 即可:
function Eraser() {} Eraser.prototype.printName = function () { console.log('this is an eraser'); }; 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),因此僅憑參數名來判斷依賴並不總是可靠。這時,我們也可以為函數添加額外屬性來明確聲明其依賴:
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 || 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 的讀者很快就能聯想到:在依賴注入之前,我們在定義 module 時還可以呼叫 config 方法來配置稍後會被注入的物件,最典型的例子莫過於使用路由時對 $routeProvider 的配置。也就是說,不同於上一節直接把現成物件(如 new Notebook())存入 cache,AngularJS 的依賴注入還經歷了一個「實例化」或「呼叫工廠方法」的過程。
這正是 providerInjector、instanceInjector,以及它們各自持有的 providerCache 與 instanceCache 的由來。
在 AngularJS 中,我們平時能取得的 injector 通常是 instanceInjector,而 providerInjector 則以閉包變數的形式存在。當我們需要某個依賴(比如 notebook)時,instanceInjector 會先查詢 instanceCache 上是否存在 notebook 屬性;若存在則直接注入,若不存在則把任務轉交給 providerInjector。providerInjector 會把「Provider」字串拼接到「notebook」之後,組成新的鍵名「notebookProvider」,再到 providerCache 中查詢。若查無此屬性,便拋出 Unknown Provider 異常。
如果存在,providerInjector 會將這個 provider 返回給 instanceInjector;後者拿到 notebookProvider 後,會呼叫它上面的工廠方法 $get 取得 notebook 物件,將其存入 instanceCache 以備將來使用,同時注入到最初宣告該依賴的函數中。
需要注意的是,AngularJS 的這種依賴注入方式也有其侷限:用單一 instanceInjector 單例服務於全域,副作用是難以單獨追蹤與控制某一條依賴鏈條;即便在沒有交叉依賴的情況下,不同 module 中的同名 provider 也會相互覆蓋。
此外,對於習慣了 Java、C# 等高階 IoC 容器的讀者而言,這種把依賴以參數形式傳給方法的方式或許有些別扭。畢竟在物件導向實踐中,我們通常不會把依賴當作參數傳遞,而是透過建構子或 setter 作為屬性注入到實例中,以實現封裝。第一、二節的方式確實沒能充分展現物件導向特性——畢竟它們在 JavaScript 中已存在多年,甚至不需要 ES5 的語法支援。想了解近一兩年 JavaScript 社群在依賴注入上的新成果,不妨繼續往下閱讀。
三、TypeScript 中基於裝飾器與反射的依賴注入
對於 JavaScript 的各種方言,筆者的學習熱情其實並不算高,尤其是 ECMAScript 提案更新頻繁,很多時候靠 polyfill 與 babel 的各類 preset 就能滿足需求。但 TypeScript 是個例外(如今 Decorator 也已是提案,雖階段較早,卻已有可用的 polyfill)。既然 JavaScript 社群遲遲未能誕生優秀的 IoC 容器與語言特性有關,那麼就依賴注入這個話題而言,TypeScript 究竟帶來了什麼不同?至少有以下幾點:
· TypeScript 增加了編譯期型別檢查,讓 JavaScript 具備了一定的靜態語言特性
· TypeScript 支援裝飾器(Decorator)語法,與傳統的注解(Annotation)頗為相似
· TypeScript 支援元資訊(Metadata)反射,不再需要呼叫 Function.prototype.toString
下面我們就嘗試借助 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 中取出對應依賴。至於 dependenciesMap 中的依賴關係是何时存入的,則是裝飾器 Inject 的職責,稍後再談。取出依賴後,由於它們已是建構子的引用(如 Notebook、Pencil 的建構子)而非單純的字串,因此直接 new 即可建立物件。最後,如何把這些依賴作為參數傳入 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(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,需要對 TypeScript 裝飾器的原理與 Array.prototype 上的 reduce 方法有較到位的認識。
function RadicalInject(...dependencies){ var wrappedFunc:any = function (target: any) { dependencies = dependencies.map(function (dependency) { return new dependency(); }); function mockConstructor() { target.apply(this, dependencies); } mockConstructor.prototype = target.prototype; // 使用 RadicalInject 裝飾後,Student 指向的已非最初的 class Student, // 而是此處的返回值 reservedConstructor。為保證 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 的建構子需要接收三個參數,直接無參呼叫 new Student() 會導致 TypeScript 編譯器報錯。這裡只是分享一種思路,讀者暫可忽略該錯誤;有興趣的朋友也可以嘗試代理一個工廠方法而非直接代理建構子,以規避這類問題。
值得一提的是,AngularJS2 團隊為了獲得更好的裝飾器與反射語法支援,一度準備另起爐灶、基於 AtScript 開發新框架,但最終選擇擁抱 TypeScript,於是便有了微軟與谷歌的奇妙組合。當然也要說明:在缺乏相關標準與瀏覽器廠商支援的情況下,TypeScript 在執行期其實只是純粹的 JavaScript,下一節的例子將印證這一點。
四、inversify.js——JavaScript 技術棧中的 IoC 容器
其實,從 JavaScript 出現各種支援高階語言特性的方言,就不難預見 IoC 容器的誕生只是早晚之事。基於 TypeScript 的 inversify.js 正是其中的先行者之一。
inversify.js 比上一節的例子先進許多,它最初的設計目標,就是讓前端工程師能在 JavaScript 中寫出符合 SOLID 原則的程式碼,立意不可謂不高。體現在程式碼中,便是處處可見介面,將「Depend upon Abstractions. Do not depend upon concretions.」(依賴於抽象,而非依賴於具體)發揮得淋漓盡致。由於 inversify.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...'); } } 有了 inversify 框架,這次我們不必再自行實作 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 的各種概念只是語法糖嗎?不同於上一節直接把建構子引用傳給 Inject,由於 inversify.js 面向介面,而 NotebookInterface、PencilInterface 這類介面只是 TypeScript 提供的語法糖,在執行期並不存在,因此我們在裝飾器中宣告依賴時只能用字串形式而非引用形式。好在 inversify.js 提供了 bind 機制,在介面的字串形式與具體建構子之間搭建起橋樑:
import { TypeBinding, Kernel } from "inversify"; var kernel = new Kernel(); kernel.bind(new TypeBinding("NotebookInterface", Notebook)); kernel.bind(new TypeBinding("PencilInterface", Pencil)); kernel.bind(new TypeBinding("EraserInterface", Eraser)); kernel.bind(new TypeBinding("StudentInterface", Student)); 這一步需要從 inversify 模組引入 TypeBinding 與 Kernel,並且為了讓回傳值型別以及整體的編譯期靜態型別檢查順利通過,還用上了泛型語法。理解了這一點,new TypeBinding("NotebookInterface", Notebook) 也就好懂了:它為依賴於「NotebookInterface」字串的類提供 Notebook 類的實例,回傳值向上溯型到 NotebookInterface。
完成這些步驟後,使用起來也頗為順手:
var student: StudentInterface = kernel.resolve("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 最後,順帶一提 ECMAScript 相關提案的現狀。Google 的 AtScript 團隊曾提出過 Annotation 提案,但隨著 AtScript 流產,該提案自然也無疾而終。目前較有希望成為標準的,是一個關於裝飾器的提案。有興趣的讀者可以到對應的 GitHub 頁面追蹤了解。
DI 雖只是物件導向眾多模式與特性中的一環,卻足以折射出 JavaScript 在物件導向道路上艱難前行的足跡。總體而言,可謂路途坦蕩、前途光明。一邊是翹首以盼的 JavaScript 社群,一邊是姗姗來遲的 IoC 容器,二者最終會碰撞出怎樣的火花,讓我們拭目以待。