JavaScript: Is window.spam good practice?

I noticed everywhere that people mention “ Just define a variable at the top of your JS code and it will become global ” in response to questions such as “ How do I create a global variable from within a function? ”. Most of the answers begin with the fact that it is impossible to achieve this. Of course, this can be done:

<script type="text/javascript">
    window.spam = 'Hello World';
</script>

Then, in your code, you can say:

<script type="text/javascript">
    alert(spam);
</script>

This works great in IE6 +, Firefox, Chrome, Safari, etc. So why does no one do this?

In my case, I want people to access a global variable with a name fooBarfrom anywhere in their code and in my AJAX library, I want the variable to automatically update behind the scenes, so when they say $.do_some_magic()they can fooBarreflect what changes made $.do_some_magic()without thinking about it. I don’t want them to have to create an up variable in their code, nor do I want to create an up variable in my library code. I suppose I just hate defining global variables at the top and would prefer if there is no good reason not to. There is?

+3
source share
2 answers

Clarity

, .

// Unclear: Intentional, or accident
function privateScope() {
  spam = "hello";

  function globalFunction() {

  }
}

global , ​​ , , .

// Clear: Intentional global use
function privateScope() {
  window.spam = "hello";

  window.globalFunction = function () {

  }
}

.

, , :

var spam;

, window.spam:

(function(){
    // currently private to this scope
    var spam;

    ... lots of code ...

    // Expose the variable publically
    window.spam = spam;
})();

anthares , collision

. , :

(function(){
   // Expose a single top level variable
   window.YourCompany = { };

   // Private:
   var spam = "name";

   ... other code ...


   // Make public
   window.YourCompany.spam = spam;

})();
+6

, window.spam. , spam. spam .

, var, , ECMAScript Fifth Edition.

var " , , " ". :

function setFooTo6() {
    fooBar= 6;
}

var fooBar;

, .

+3

Source: https://habr.com/ru/post/1731800/


All Articles