为什么设置一个应用程序变量angularJS一个“坏习惯”?变量、应用程序、习惯、angularJS

2023-09-13 04:39:15 作者:成长中的坚强

我看了一些angularJS教程和风格指南,并已发现了这样的评论(的)

 错误:VAR应用= angular.module('应用',[]);app.controller();app.factory();好:角  .module('应用',[])  .controller()  。厂(); 

我第一次学会了例如坏技术,后来看到一对夫妇的参考(除了这一个)说,坏的技术是......好不好。

没人至今在我的搜索说为什么它是坏的?

编辑: 为什么这个问题不同的的而差异是本和所提出的重复问题之间微妙的,有两个重要的区别:

什么是最好的做法?是不一样的为什么不好?......而接受的答案其他问题阐述了为什么,具有相同的回答这两个问题没有足够的品牌被重复。

JAVA技术分享 环境变量path配置

一个有力的搜索,使用我把作为标题对这个问题并没有透露建议的重复的确切文本。也许SE应该考虑允许可选的标题被添加到一个问题,以提高searchablity ...但该功能不到位和别人问同样的问题和我仍然找不到其他的问题。

解决方案

在一般的全局变量往往被认为是不好的做法,虽然本身是一个全局变量,所以我认为这是不是诚实的是的大不了的,只要你是一致的。

如果你做这样的事情不小心,可能会出现问题:

 应用程序= angular.module(应用程序);//其他一些文件应用= somethingNotAnAngularModule(); 

外部库可能会覆盖变量应用,等等等等。

而不是使用名称应用,你也可以使用一个名称,具体到你的应用程序...

  dustrModule = angular.module(dustr,[]); 

链接是一回事,但如果你分手了组件​​集成到单独的文件,你可以随时 GET 的与模块 .module

  // app.jsangular.module(应用程序,[]);// LoginCtrl.jsangular.module(应用程序),控制器(LoginCtrl,L​​oginCtrl)。 

I've looked at a number of angularJS tutorials and style guides and have found comments like this (from Todd Motto)

Bad:
var app = angular.module('app', []);
app.controller();
app.factory();

Good:
angular
  .module('app', [])
  .controller()
  .factory();

I first learned the "Bad" technique by example and have since seen a couple of reference (other than this one) that say the "Bad" technique is ...well Bad.

Nobody so far in my searches says WHY it is bad?

Edit: Why is this question different? While the differences are subtle between this and the proposed duplicate question, there are two important differences:

'What is the best practice?' is not the same as 'Why is it bad?'...while the accepted answer to the other question elaborates on 'Why', the two questions having the same answer is not sufficient be branded a duplicate.

A vigorous search, using the exact text that I placed as the title to this question did not reveal the proposed duplicate. Perhaps SE should consider allowing "optional titles" to be added to a question to enhance searchablity...but that feature is not in place and someone else asking the same question as mine will still not find the other question.

解决方案

Global variables in general tend to be considered bad practice, although angular itself is a global variable so I think that it's honestly not that big of a deal as long as you are consistent.

Problem can arise if you do something like this accidentally:

app = angular.module("app");
// some other file
app = somethingNotAnAngularModule();

External libraries might overwrite the variable app, etc. etc.

Instead of using the name app, you could also use a name that is specific to your app...

dustrModule = angular.module("dustr", []);

Chaining is one thing, but if you are splitting up components into separate files you can always get the module with .module

// app.js
angular.module("app", []);

// LoginCtrl.js
angular.module("app").controller("LoginCtrl", LoginCtrl);