JavaScript的:变量的作用域和放大器;全局的罪恶 [英] Javascript: variable scope & the evils of globals

查看:91
本文介绍了JavaScript的:变量的作用域和放大器;全局的罪恶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尽力了,我真的很,但我看不出怎么办呢:)

I'm trying to be good, I really am, but I can't see how to do it :)

如何不使用全局这里将是极大的AP preciated任何意见。让我们把全球-G。

Any advice on how to not use a global here would be greatly appreciated. Let's call the global G.

Function A 
  Builds G by AJAX

Function B
  Uses G

Function C
  Calls B
  Called by numerous event handlers attached to DOM elements (type 1)

Function D
  Calls B
  Called by numerous event handlers attached to DOM elements (type 2)

我不知道怎样才能用一个全球性的在这里得到解决。在DOM元素(类型1和2),在其他功能上创建(E&安培; F)这是不连接答:我不想与G添加到每个事件处理程序(因为它的大,还有很多这些事件处理函数) ,而这样做需要同样的解决方案,因为我正在寻找在这里(即获得G以E&安培; F)。

I can't see how I can get around using a global here. The DOM elements (types 1 & 2) are created in other functions (E&F) which are unconnected with A. I don't want to add G to each event handler (because it's large and there's lots of these event handlers), and doing so would require the same kind of solution as I'm seeking here (i.e., getting G to E&F).

全局G,顺便说一句,是一个数组,它是必要建立其他元素,因为他们,反过来,由AJAX构建。

The global G, BTW, is an array that is necessary to build other elements as they, in turn, are built by AJAX.

我不相信,一个单身是真正的解决方案,无论是。

I'm not convinced that a singleton is real solution, either.

感谢。

推荐答案

坚持,当然一切都在一个大的立即执行的功能,!

Stick everything in one big immediately-executing function, of course!

(function() {
    // Your code goes here
})(); // Called right away

您可以在里面放任何东西,它会接触到在一个较窄的范围内什么,但他们仍然不会是全球性的。

You can put anything in there and it will be accessible to anything in a narrower scope, but they still won't be global.

另外,如果你是唯一的文件,停止避免全局,因为真的没有伤害,除非你正在做一些可重复使用的组件。

Also, if yours is the only file, stop avoiding globals because there's really no harm unless you're making some kind of reusable component.

这篇关于JavaScript的:变量的作用域和放大器;全局的罪恶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆