Are global variables created until the document is ready?

If I declare a global variable immediately after the script tag, is it safe to access this variable in a function called in the document ready?

<script type="text/javascript"> var bar = "foo"; $(document).ready(function(){ callBar() }); function callBar(){ alert(bar); // will I crash? } </script> 

what then if i do this:

 <script type="text/javascript"> $(document).ready(function(){ callBar() }); function callBar(){ alert(bar); // will I crash? } var bar = "foo"; </script> 
+4
source share
4 answers

is it safe to access this variable in a function called a finished document

Yes. A variable is declared ( added as a binding to the execution context variable environment) as a very early stage in the execution of this script. (Note that it is not actually assigned a value until the assignment operator is reached during parsing. This is usually called a โ€œraiseโ€, but does not affect your example).

Since the execution of the script is executed synchronously (the browser will stop rendering until it has completed the parsing and execution of the script element), the DOM ready event will not fire until this execution is complete.


Edit (question updated)

what then if i do this ...

As described above, a variable declaration will be raised at the top of the scope. Your second example is effectively interpreted as follows:

 // Declarations (both function and variable) are hoisted var bar; function callBar() { alert(bar); } $(document).ready(function () { callBar(); }); bar = "foo"; 

Therefore, these ads are available throughout. The finished event handler will be executed after a while and will have access to these announcements (since they appeared in the same volume as he).

+6
source

Since bar declared in global scope, I expect it to be initialized before calling callBar .

Also think that JavaScript has a hoisting function that allows you to refer to variables if they are in the correct area, even if they are defined later in the program (although this is not the case). From MDN documents to Scope :

Another unusual thing about variables in JavaScript is that you can reference a variable declared later without receiving an exception. This concept is called ascent; variables in JavaScript are, in a sense, โ€œraisedโ€ or raised to the top of a function or statement. However, variables that are not yet initialized return an undefined value.

0
source

Yes, even before the tag 'close'.

The function inside '$ (document) .ready (function () {})' is built after loading all pages.

0
source

Work with the global safe variable.

But you need to be careful when using global variables in jQuery

Use Window.bar="foo" instead of var bar="foo" for more information. The best ways to use global variables in jQuery

I used a global variable and is really useful.

0
source

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


All Articles