首页 > Angular.js Dependency Injection 的实现原理是什么?

Angular.js Dependency Injection 的实现原理是什么?

The simplest way to get hold of the dependencies, is to assume that the function parameter names are the names of the dependencies.

function MyController($scope, greeter) {
  ...
}

Given a function the injector can infer the names of the service to inject by examining the function declaration and extracting the parameter names. In the above example $scope, and greeter are two services which need to be injected into the function.

上文是在Dependency Injection这篇Guide中截去的原文。其中讲到如果Controller需要某样服务,则只需在他构造函数的参数里添加并指定正确的名称就行了。像上面的例子里,Angular会自动寻找$scope和greeter这两个服务,并传递给函数。
但是令我不解的是,Angular是如何知道MyController签名(参数)的?和Function参数相关的变量似乎只有arguments,但这个变量只能在函数内部使用,在外部调用会返回null。

function ACtrl(paramA,paramB){}
ACtrl.arguments
 //null

那么,Angular到底是如何知道函数签名(参数)的?


AngularJS 是通过静态编译来分析参数的。

function ACtrl(paramA,paramB){}
ACtrl.toString()
"function ACtrl(paramA,paramB){}"

通过对函数 toString() 操作,获取到函数全部内容,然后进行编译处理。

坏处是不抗压缩。

【热门文章】
【热门文章】