2014-04-17 292 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"]