Global objects

We all know that there is a very important class of objects in JavaScript, the Global object, whose properties are globally defined symbols that we can use directly when writing JavaScript code. When the JavaScript interpreter starts (when the browser loads a new page), it creates a new global object and defines an initial set of properties:

  • Global properties, such asundefined,InfinityandNaN
  • Global functions such asisNaN(),parseInt()andeval()
  • Constructor, as inDate(),RegExp(),String(),Object()andArray()
  • Global objects such asMathandJSON

At the very top of the code — in JavaScript code that is not inside any function — we can use this to refer to global objects:

var global = this; // Define a global variable that refers to a global objectCopy the code

In browsers, the Window object acts as a global object, and its Window property refers to itself instead of this. The Window object also defines additional global properties for the Web browser and client-side JavaScript. In addition, when we declare a global variable in our code, the global variable is an attribute of the global object.

Second, the execution environment

The execution environment is arguably the most important concept in JavaScript.

The execution environment defines other data that variables or functions have access to, and determines their respective behavior.

Each execution environment has a variable object associated with it. All variables and functions defined in the environment are stored in this object, but this object is not accessible to us. It is only used behind the scenes by the parser to process data.

Global execution environment – the most peripheral execution environment. In the browser, the global execution environment is the global object Window, so all global variables and functions can be used as properties and methods of the Window object; Function execution environment – Each function has its own execution environment. When the code executes to a function, the environment of the function is pushed into an environment stack. When the function is finished, the environment stack pops up its execution environment and returns control to the previous execution environment. The order in which JavaScript code is executed is controlled by this mechanism. Garbage collection – When an execution environment is popped from the environment stack, the environment is destroyed, and all variables and function definitions saved in it are also destroyed to free memory. This is JavaScript’s automatic garbage collection mechanism. Only the program exits and global execution environment, such as turning off the web will be destroyed, so for a global variable or global attribute of an object, once we no longer need to use them, you can manually set its value to null to remove the reference, once the reference is lifted, they will be out of the execution environment, so that the garbage collector runs its recycling, This is a good way to optimize memory footprint.

Scope

1. Variable scope

The scope of a variable is the area in which the variable is defined in the code. Global variables have global scope and are defined anywhere. Variables declared in a function are defined only in the function body. They are local variables and have local scope. Function parameters are also local variables, defined only within the body of a function. In the function body, local variables take precedence over global variables. If a variable declared in a function or a function parameter has the same name as the global variable, the global variable will be overwritten by the local variable. Local variables must be declared using the VAR statement

scope = "global";
function checkscope () {
    scope = "local"; // Changed the global variable myscope ="local"; // The display declares the new global variablereturn[scope, myscope]; } checkscope(); / / /"local"."local"]
console.log(scope, myscope)     // "local"."local"
Copy the code

2. Function scope

In other languages like C, curly bracketed blocks of code have their own scope, equivalent to the execution environment in JS. There is no block-level scope in JS. Instead, JS uses function scope, which means variables are defined in the body of the function that declares them and in any nested function within that function.

function test(o) {
    if(o) { var i = o; // I is defined in the body of a function, not just inifInside this code snippetfor(var j = 0; j < 10; J ++) {// j is defined in the body of a function, not just inforCirculation within the console. The log (j); // Output 0~9} console.log(j); // j is already defined, output 10} console.log(I); // I is defined, but may not be initialized}Copy the code

3. Announce early

We know that under JavaScript’s function scope, all variables declared inside a function are always visible inside the function body, and we may have some misunderstandings due to this feature. Let’s start with some code:

var scope = "global";
function f() { console.log(scope); / / output"undefined"Rather than"global"
    var scope = "local"; // The variable is assigned an initial value here, but the variable itself is console.log(scope) defined anywhere in the function body; / / output"local"
}
Copy the code

You might think that the first line of the function prints global, but it doesn’t, and that’s where it gets confused. Due to the nature of function scope, local variables are always defined throughout the function body, which means variables can be used before they are declared. This feature is called “declaration advance” — that is, variable declarations within a function are “brought forward” to the top of the function body, while variable initializations remain where they were. So the code for the above function is actually equivalent to:

function f() { var scope; Console. log(scope) is declared at the top of the function; // The variable exists, but its value is"undefined"
    scope = "local"; // Initialize the variable and assign console.log(scope); }Copy the code

Note:

  • “Declare ahead” is done during the “precompile” phase of the JavaScript engine, before the code starts to run.
  • Because JavaScript has no block-level scope, variable declarations are usually placed at the top of the function body, which makes our code more clearly reflect the real scope of the variable.

At the end

Series of articles:

  • JavaScript is new from the past — prototypes and prototype chains
  • JavaScript is old and new — execution environment and scope
  • JavaScript is old and new — scoped chains and closures
  • JavaScript: 4 ways to call a function
  • JavaScript revisits the past — the implementation of call() and apply()