Javascript : pattern to avoid global variables

放肆的年华 提交于 2020-01-15 03:47:06

问题


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>

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>

Thank you.


回答1:


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");
}



回答2:


You could put the loading AJAX function inside of the anonymous function that is executed when the DOM has loaded along with the channel variable. Both will then be scoped only to the anonymous function and scopes therein.



来源:https://stackoverflow.com/questions/5072667/javascript-pattern-to-avoid-global-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!