Global object

Lecture




  1. Global object
  2. Initialization order
  3. Total

The mechanism of operation of functions and variables in JavaScript is very different from most languages.

To understand it, we will look at variables and functions in the global scope in this chapter. And in the next - let's go further.

Global object

Global are variables and functions that are not inside a function. That is, in other words, if a variable or function is not inside a function construct, then they are “global”.

In JavaScript, all global variables and functions are properties of a special object called a global object .

In the browser, this object is clearly available under the name window . The window object is also a global object and contains a number of properties and methods for working with a browser window, but we are only interested in its role as a global object.

In other environments, such as Node.JS, the global object may not be available explicitly, but the essence of what is happening from this does not change, therefore, we will use "window" to denote the global object.

Assigning or reading a global variable, we actually work with the window properties.

For example:

1 var a = 5; // объявление var создаёт свойство window.a
2 alert(window.a); // 5

You can create a variable by explicit assignment in a window :

1 window.a = 5;
2 alert(a); // 5

Initialization order

The execution of the script occurs in two phases:

  1. In the first phase, initialization takes place, preparing for launch.

    During initialization, the script is scanned for the declaration of functions of the type Function Declaration, and then for the declaration of var variables. Each such ad is added to the window .

    Functions declared as Function Declaration are created immediately, and variables equal to undefined .

  2. In the second phase - actually, implementation.

    The assignment ( = ) of variable values ​​occurs in the second phase, when the execution flow reaches the corresponding line of code.

At the beginning of the code below is the content of the global object at the time of the initialization:

1 // По окончании инициализации, до выполнения кода:
2 // window = { f: function, a: undefined, g: undefined }
3
4 var a = 5; // при инициализации даёт: window.a=undefined
5
6 function f(arg) { /*...*/ } // при инициализации даёт: window.f = function
7
8 var g = function (arg) { /*...*/ }; // при инициализации даёт: window.g = undefined

By the way, the fact that by the beginning of the code execution variables and functions are already contained in the window can be easily checked:

1 alert( "a" in window); // true , т.к. есть свойство window.a
2 alert(a); // равно undefined , присваивание будет выполнено далее
3 alert(f); // function ... , готовая к выполнению функция
4 alert(g); // undefined , т.к. это переменная, а не Function Declaration
5
6 var a = 5;
7 function f() { /*...*/ }
8 var g = function () { /*...*/ };

Assigning a variable without a declaration

In the old JavaScript standard, a variable could be created without a var declaration:

1 a = 5;
2
3 alert(a); // 5

Such an assignment, like var a = 5 , creates the window.a = 5 property. The difference from var a = 5 is that the variable will be created not at the stage of entering the scope, but at the moment of assignment.

Compare the two codes below.

The first one will display undefined , since the variable was added to the window during the initialization phase:

1 alert(a); // undefined
2
3 var a = 5;

The second code will print an error, because the variable does not exist yet:

1 alert(a); // error, a is not defined
2
3 a = 5;

In general, it is recommended to always declare variables through var .

In the modern standard, assignment without a var will cause an error:

1 'use strict' ;
2 a = 5; // error, a is not defined

Constructions for, if... do not affect the visibility of variables

Curly brackets, which are used in for, while, if , unlike function declarations, have a “decorative” character.

In JavaScript, there is no difference between a declaration outside of a block:

1 var i;
2 {
3    i = 5;
4 }
... And inside it:
1 i = 5;
2 {
3    var i;
4 }

There is also no difference between the declaration in the loop and outside it:

1 for ( var i=0; i<5; i++) { }
Identical in functionality code:
1 var i;
2 for (i=0; i<5; i++) { }

In both cases, the variable will be created before the loop is executed, at the initialization stage, and its value will be saved after the end of the loop.

It doesn't matter where and how many times the variable is declared.

var ads can be any number of:

1 var i = 10;
2
3 for ( var i=0; i<20; i++) {
4    ...
5 }
6
7 var i = 5;

All var will be processed once, during the initialization phase.

During the execution phase, var declarations will be ignored: they have already been processed. But assignments will be made.

Errors when working with window in IE8-

In old IE, there are two funny errors when working with variables in a window :

  1. Redefining a variable with the same name as the element id will result in an error:
    1 < div id = "a" >...</ div >
    2 <script>
    3    a = 5; // ошибка в IE<9! Правильно будет "var a = 5"
    4    alert(a); // никогда не сработает
    5 </script>

    And if done through var , then everything will be fine.

    It was an advertisement for putting var everywhere.

  2. An error occurred during recursion through the window property function. The following code will "die" in IE <9:
    1 <script>
    2 // рекурсия через функцию, явно записанную в window
    3 window.recurse = function (times) {
    4    if (times !== 0) recurse(times-1);
    5 }
    6
    7 recurse(13);
    8 </script>

    The problem here arises from the fact that the function is directly assigned in window.recurse = ... It will not be in the normal function declaration.

    This example will generate an error only in true IE8! Not IE9 in emulation mode. In general, the emulation mode allows you to catch somewhere 95% of incompatibilities and problems, and for the remaining 5% you will need a real IE8 in the virtual machine.

Total

As a result of initialization, to the beginning of the code execution:

  1. Functions declared as Function Declaration are completely created and ready to use.
  2. Variables are declared but equal to undefined . Assignments will be executed later when execution reaches them.

Importance: 5

What will be the result of the code?

1 if ( "a" in window) {
2      var a = 1;
3 }
4 alert(a);

Decision

Answer: 1 .

1 if ( "a" in window) {
2      var a = 1;
3 }
4 alert(a);

Let's see why.

At the preparatory stage for execution, window.a is created from var a :

1 // window = {a:undefined}
2
3 if ( "a" in window) { // в if видно что window.a уже есть
4      var a = 1; // поэтому эта строка сработает
5 }
6 alert(a);

As a result, a becomes 1 .

[Open task in new window]

Importance: 5

What will be the result (before a no var )?

1 if ( "a" in window) {
2      a = 1;
3 }
4 alert(a);

Decision

Answer: an error .

There is no variable a , so the condition "a" in window will not be fulfilled. As a result, the last line is a call to an undefined variable.

1 if ( "a" in window) {
2      a = 1;
3 }
4 alert(a); // <-- error!

[Open task in new window]

Importance: 5

What will be the result (before a there is no var , and below it is)?

1 if ( "a" in window) {
2      a = 1;
3 }
4 var a;
5
6 alert(a);

Decision

Answer: 1 .

The variable a is created before the start of the code execution, so that the condition "a" in window fulfilled and the a = 1 triggered.

1 if ( "a" in window) {
2      a = 1;
3 }
4 var a;
5
6 alert(a); // 1

[Open task in new window]

Importance: 3

What will be the result of the code? Why?

1 var a = 5;
2  
3 function a() { }
4
5 alert(a);

PS This task is educational, for understanding the process of initialization and execution. In real life, of course, we will not call the variable and function the same.

Decision

Answer: 5 .

1 var a = 5;
2  
3 function a() { }
4
5 alert(a);

To understand why, let's look at how this code works.

  1. Before execution starts, the variable a and the function a . The standard is written in such a way that the function is created first and the variable does not overwrite it. That is, the function takes precedence. But in this case it doesn't matter at all, because ...
  2. ... After initialization, when the code starts to execute - assignment a = 5 works, overwriting a , and it does not matter what lay there.
  3. Function Declaration declaration declaration at execution stage is ignored (already processed).
  4. As a result, alert(a) displays 5.
created: 2014-10-07
updated: 2021-03-13
132585



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone