通過使用工廠的方法,你幾乎告訴AngularJS,每當被請求的DateFormatter
的對象(例如,通過依賴注入機構),但是應該執行傳遞給第二個參數factory(..., ...)
的方法中,並提供該函數返回的對象而不是函數本身。
也就是說,Angular不會提供您定義的方法,而是該方法返回的對象。這幾乎是'工廠'這個詞的意思:'當我要求時爲我創建這個對象'。
如果返回的功能,一切會改變的是你將不得不自行調用該函數,以便它提供了一些值/對象,比如這個:
.controller(DateFormatter) {
// If Angular returned the function rather than it's returned value,
// you would have to do this in order to get access to the clean function:
(DateFormatter()).clean();
}
在另一種意義上說,你認爲它使得clean
函數可用是正確的。爲此,它還提供了一種封裝機制。如果你這樣做:
angular.module('someModule')
.factory('DateFormatter', function() {
var clean = function (date) {
date = someHelperFunction(date);
return moment(date).format('YYYY-MM-DD');
};
var someHelperFunction(date) {
// do something here with date
};
return {
clean:clean
};
});
那麼你就能夠從內部調用someHelperFunction
功能,而不是從外面,因爲你沒有返回。