【发布时间】:2017-03-06 20:39:12
【问题描述】:
阅读angular docs on dependency injection,有两种适合缩小的方法:
- 内联数组注释:
module.factory("MyStuff",['dependency',function(dep){...}]) -
$inject属性:function MyStuff(dep) {...} MyStuff.$inject = ['dependency']; module.factory("MyStuff",MyStuff);
推荐使用内联的(第一个)。在我的一个项目中,风格指南坚持使用$inject 属性。我还经常在开源代码中看到$inject 属性形式。
因此问题:
使用$inject 属性表单有哪些实际或技术优势?
我想出了两个,但它们看起来不太合法:
- 直接创建
MyStuff的实例:new MyStuff(someOtherDependency).foo(...); - 在
console.log(myStuffInstance)中有函数名
还有什么我遗漏的吗?
【问题讨论】:
-
为了可读性,建议保持清晰的关注点分离。
-
刚刚有人评论了ng-annotate (github.com/olov/ng-annotate),值得一提...
-
是的,
ng-anotate用于为生产模式自动添加压缩友好注入的任务,因此您不必添加['$scope', ..., function ($scope, ...]或myFactory.$inject['$scope, ...。在构建到生产环境时,它会添加对缩小友好的注入。
标签: javascript angularjs dependency-injection inject