2014-04-17 291 views
0

在AngularJS中自動解析依賴關係背後的魔力是什麼?AngularJS依賴注入原理

angular 
    .module('app', []) 
    .service('appService', 
     function appService (firstService, secondService, thirdService) { } 

如何firstService,secondService,thirdService自動注入?

+1

看看http://www.alexrothenberg.com/2013/02/11/the-magic-behind-angularjs-dependency-injection.html – Whisher

回答

1

JavaScript自動依賴注入基於Function.prototype.toString()方法,該方法以函數聲明的形式返回對象的字符串表示形式。

返回的字符串使用正則表達式進行分析,以查找函數參數並返回將用於查找,實例化和注入實際服務的名稱。

(function appService (firstService,secondService,thirdService) {}) 
    .toString() 
    .match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1] 
    .split(',') 

// => ["firstService", "secondService", "thirdService"]