所以在AngularJS 文档中,我看到了关于注入器的内容:
// You write functions such as this one.
function doSomething(serviceA, serviceB) {
// do something here.
}
// Angular provides the injector for your application
var $injector = ...;
///////////////////////////////////////////////
// the old-school way of getting dependencies.
var serviceA = $injector.get('serviceA');
var serviceB = $injector.get('serviceB');
// now call the function
doSomething(serviceA, serviceB);
///////////////////////////////////////////////
// the cool way of getting dependencies.
// the $injector will supply the arguments to the function automatically
$injector.invoke(doSomething); // This is how the framework calls your functions
看起来很好。但我不明白。在注入器查找依赖项的最后一行中,它不完全像拥有全局变量 serviceA、serviceB 吗?我的意思是,说我会这样重写它:
var serviceA, serviceB;
function doSomething() {
// access serviceA, serviceB
}
让注射器这样做有什么好处?我的意思是,如果他可以神奇地为参数找到正确的对象,这是否意味着如果它们是全局变量,我可以很容易地找到它们?
我希望我的问题很清楚...