When I use major communities to check knowledge about Angular, I often see two modes of dependency injection, some of which are controller.('Ctr',[$scope,function($scope){...}] );
Some are directly controller.('Ctr',function($scope){...});
I would like to ask if this latter mode is new and universal?
光陰似箭催人老,日月如移越少年。
The best practice is to use: controller.('Ctr',['$scope',function($scope){...}]).
As @Deboy said, for js compression.
Better performance. (controller.('Ctr',function($scope){...}), angularjs will parse the parameters of this function, and finally get the content to be injected, while the array-style writing method can skip the parsing step, and the performance will be better). Attached is the source code for reference:
function annotate(fn, strictDi, name) {
var $inject,
fnText,
argDecl,
last;
if (typeof fn === 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
if (fn.length) {
if (strictDi) {
if (!isString(name) || !name) {
name = fn.name || anonFn(fn);
}
throw $injectorMinErr('strictdi',
'{0} is not using explicit annotation and cannot be invoked in strict mode', name);
}
fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS);
forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
arg.replace(FN_ARG, function(all, underscore, name) {
$inject.push(name);
});
});
}
fn.$inject = $inject;
}
} else if (isArray(fn)) {
last = fn.length - 1;
assertArgFn(fn[last], 'fn');
$inject = fn.slice(0, last);
} else {
assertArgFn(fn, 'fn', true);
}
return $inject;
}
Because in the process of front-end optimization, files such as js will be compressed and some strings will be replaced with single letters. If this is the case, angular injection will fail. The latter one is not processed to prevent injection after compression. The previous one did this, so even if it is compressed, it will not cause the injection to fail
The effects of the two executions during the development phase are the same
angular
的依賴注入的實(shí)現(xiàn)方式,沒有什么規(guī)范/標(biāo)準(zhǔn)可談,但卻是不錯(cuò)的思路。
我之前寫過一篇教程,教你手寫一個(gè)類似angular
’s dependency injection system, I hope it will be useful to you: BDD handwritten dependency injection