[removed] pattern to avoid global variables

2019-07-12 20:37发布

问题:

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.