为什么全局函数被认为是

为什么全局函数被认为是

本文介绍了为什么全局函数被认为是“错误的"?在 Angular 1.3 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

传统上我是这样管理我的 Angular 代码的

Traditionally I have managed my Angular code like this

//File 1
angular.module('name',[])
//File 2
function TestController(){

}
TestController.prototype.// inherited stuff
angular.module('name').controller('testController',TestController);

这很好用,让我可以轻松地对文件进行分区.现在我尝试升级到 1.3 并获得臭名昭著的...

This worked great and allowed me to partition my files easily. Now I try to upgrade to 1.3 and get the infamous...

Error: [ng:areq] Argument 'TestController' is not a function, got undefined

当然这是由于这一变化,它声称希望清理人们编写代码的方式.这个模式比较复杂怎么办?有没有办法在不改变全局设置的情况下保持这种模式?

Of course this is due to this change which claims a desire to clean up the way people write code. What about this pattern is more complex? Is there a way to maintain this pattern without changing the global settings?

推荐答案

其实有一个您链接到的页面上的评论有相当可靠的解释.

There is actually a comment on the page you linked to that had a fairly solid explanation.

全局控制器是指您的控制器被定义为函数在窗口对象上.这意味着它们可以公开提供给与碰巧定义一个的任何其他 JavaScript 位冲突具有相同名称的函数.诚然,如果你后修复你的带有 ...Controller 的控制器,那么这很可能不会发生,但是总是有机会的,特别是如果你要使用一些第 3 方库.放置这些控制器更安全模块安全内部的功能.然后你有更多的控制权何时何地加载此模块.不幸的控制器名称在单个 Angular 应用程序中是全局的,因此您仍然有潜在的冲突,但至少你不能冲突JavaScript 全局命名空间中完全不同的代码.

所以这个想法是全局控制器函数可能与您使用的任何 javascript 中的任何其他全局函数发生冲突.因此,为了消除与您自己的代码或第三方脚本发生冲突的可能性,不使用全局控制器会使您的代码更安全、更一致.

So the idea is that global controller functions could conflict with any other global function in any javascript you use. So to eliminate the chance of a conflict with your own code or a third-party script, not using global controllers makes your code safer and more consistent.

正如@Brett 在评论中提到的,您可以在原型设计中使用 IIFE.这是使用它的 plunk 的更新.主要变化看起来像这样.

As mentioned in the comments by @Brett, you can use IIFE around your prototyping. Here is an update of your plunk that uses that. The main change just looks like this.

(function() {
  TestController.prototype.name = 'World'
})();

这篇关于为什么全局函数被认为是“错误的"?在 Angular 1.3 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:29