Javascript:避免全局变量的模式 [英] Javascript : pattern to avoid global variables
问题描述
我认为这是一个简单的问题.假设你有一个页面初始化了一个名为 channel
的 JS 变量:
I think this is a simple question. Imagine you have a page that initializes a JS variable named channel
:
<html>
<script>
$(document).ready(function() {
...
var channel = new Channel();
channel.send("helo");
}
</script>
<body>
<div id="placeholder"></content>
</body>
</html>
该页面还包含一个 id="placeholder" 的 div,其内容是使用 AJAX 加载的.外部内容必须访问 channel
变量.
The page also contains a div with id="placeholder" which content is loaded using AJAX. That external content have to access the channel
variable.
关于变量的存储位置有什么好的做法或建议吗?以下代码有效,但我不喜欢它:
Is there any good practice or advice about where to store the variable? The following code works but I do not like it:
<html>
<script>
var channel;
$(document).ready(function() {
...
channel = new Channel();
channel.send("helo");
}
</script>
...
</html>
谢谢.
推荐答案
不,在这种情况下没有其他方法,因为全局作用域是两个脚本共享的唯一作用域(嗯,我想这取决于关于您实际添加内容的方式.您是怎么做的?)
No, in this case there is no other way as the global scope is the only scope both scripts share (edit: well, I guess this depends on how you actually add the content. How do you do it?)
你唯一能做的就是通过使用对象作为命名空间来最小化全局变量的数量:
The only thing you can do is to minimize the number global variables by using an object as namespace:
var your_namespace = {};
$(document).ready(function() {
...
your_namespace.channel = new Channel();
your_namespace.channel.send("helo");
}
这篇关于Javascript:避免全局变量的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!