开发者

Javascript : pattern to avoid global variables

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 Cha开发者_高级运维nnel();
       channel.send("helo");
    }
</script>
...
</html>

Thank you.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜