所以在AngularJS docs只見這對噴油器:注射器做什麼全局變量不能?
// 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
}
注射器做這些的好處是什麼?我的意思是,如果他能夠奇蹟般地爲爭論找到正確的對象,那麼不是說如果他們是全局變量,我可以很容易地發現它們嗎?
我希望我的問題是清楚的...
我認爲真正的用途是:1)的噴射器模塊綁定(所以沒有全局變量)。 2)可測試性,這對於全球狀態將會很難。 – Yoshi
我需要寫備忘錄「Javascript全局不好」。哦,等等,它已經完成了。 ;-)並不是說它們不好,只是使用它們會增加覆蓋和碰撞的機會。另外,正如Yoshi所說,注射使測試變得更容易。 – Sharondio