Core knowledge

  1. The JavaScript language consists of three parts
  2. Overview of variables in JavaScript
  3. There are several ways to create variables and various features and differences
  4. Variable ascension
  5. Initial understanding of execution context, scope chains

The JavaScript language consists of three parts

According to the relevant JS syntax, to operate the elements in the page, sometimes also operate some functions in the browser

1–ECMAScript (ES) 3/5/6… :

  • The syntax specification of JS (variables, data types, operation statements, etc.) describes the syntax and basic objects of the language

2–DOM (Document Object Model)

  • The document object model (which describes the methods and interfaces used to process web content) provides JS properties and methods for manipulating Dom elements in a page

3–BOM (Browser Object Model) :

  • The browser object model (which describes the methods and interfaces used to interact with the browser) provides some JS properties and methods for manipulating the browser

The JavaScript variable variable

Variable: a variable quantity. In a programming language, a variable is a block of memory that stores and represents things with different values.

  • A block of memory used to store values
  • For primitive data types, the value data itself is stored in the variable’s memory space.
  • If the value to be stored is a reference data type, the value stored in this variable is the heap memory address of the value.

Several ways to create variables

var /let /const /function /class /import /Symbol

// Create a variable n based on var to point to the specific value 10
  var n = 10; 
// Create variable m, but not unassigned, default to undefined
  var m;
  console.log(n,m);//=> output 10 undefined
  let a = 100;// Create a variable called a based on let with a value of 100
      a = 200; / / modify the value
  console.log(a);/ / = > output 200
  const b = 1000; // Create variable b with value 1000 based on const
      b = 200; 
  console.log(b); Uncaught TypeError: Assignment to constant variable The pointer cannot be modified
// Create a function: you can also create a variable func that points to the function
  function func(){} 
  console.log(func);//=> output func function itself func(){}
// Create a class: create a variable Parent that points to the class
  class Parent{}
  console.log(Parent);//=> output class Parent{}
// Import a specific module based on the module specification: define a variable called axios to point to the imported module
import axios from './axios';// let axios = require('./axios');
let c = Symbol (1000) // Create a unique value
Copy the code

The characteristics and differences of each variable

  • Global variables and functions defined by var become properties and methods of the window object

  • In ES6, top-level declarations created using let and const are not defined in the global context, but the scope chain resolves the same

  • Let creates variables, but its Pointers can be changed at will.

  • Const creates a variable that looks like a constant, except that its ** can’t be changed once it’s determined. The value of a variable created by const is not allowed to be modified. Const only guarantees that the pointer is fixed. It has no control over whether the data structure it points to is mutable. Therefore, declaring a reference type (object or array) as a constant may be modified

     const a = { name: "gao"}
     let b = a;
     b.name = "zhang"
     console.log(b); //name: "zhang"
     console.log(a); //name: "zhang" a changed
    // const a = [1, 2, 3]
    // let b = a;
    // b[0] = 3; Same thing with arrays
    Copy the code
  • Function creates a Function

    • The three roles of functions
      1. Ordinary functions (scope and scope chain)
      2. Constructors (class/instance/stereotype and stereotype chain)
        • (When a function is executed as a constructor, an instance is created, and the function itself is equivalent to a class.)
      3. Plain object (key-value pair/attribute value attribute name)
  • Create Class (new syntax for creating custom classes in ES6)

  • Import a module import a module

  • Symbol (1000) creates a unique value

Variable ascension

The browser will pre-declare or define all javascript with the var/function keyword before the JS code in the current scope is executed top-down

The var keyword is just declared in advance and the function keyword is declared and defined in the variable promotion phase

 Var x; var y; Fn = xx001(heap address)
  console.log(x); //undefied
  var x = 3, y = 4;
  console.log(x);/ / 3
  console.log(fn);/ / ƒ fn () {}
  function fn() {}
Copy the code

What is the difference between defining a variable with and without var?

 console.log(a);   //undefied
 var a = 12;
 console.log(a); / / 12
 console.log(window.a); / / 12
Copy the code
 console.log(a);   //undefied
  a = 12;
 console.log(a); / / 12
 console.log(window.a); / / 12
Copy the code

With var: To declare a variable in the current scope, if it is global, it is equivalent to adding an attribute called A to the global scope, i.e. adding an attribute a to the window

Without var: A is just an attribute of Window (Window is omitted) and not a strictly variable

I only do variable promotion on the left-hand side

  • = assignment left side is variable and right side is always value]

  • A is equal to b, right? C :d but also calculate the result before the assignment

  • Anonymous function: function representation (treating a function as a value)

    console.log(fn) //undefined 
    var fn = function(){} 
    console.log(fn) // The function itself
    Copy the code
    sum(); //TypeError: sum is not a function
    var sum = function(){}
    // => "sum" is not defined yet
    fn(); // aaa
    function fn(){console.log("aaa"); } fn();// aaa
    // The notation fn has been promoted and defined so that fu() can run on or below
    Copy the code

    In a real project application of this principle can be used when we create a function expression function Such a more rigorous Because only on the left of the equals sign, so variable after the completion of the ascension The current function is statement, no want to perform functions defined only after the assignment of code execution, so let’s code is more logical

Do variable promotion regardless of whether the condition is true or not

 var aa = 1;
 function bb(){
 Private variables: var aa,var b
 aa = 33;
 console.log(aa); //33 => change the value of aa for the first time under the scope of the function
     if(1= = =1) {var b = 4; 
        var aa = 44
        // aa = 44 If var is not declared, this will change the global aa
      }
     console.log(aa,b);//44 4 => Change the aa value b for the second time to 4
  } 
  bb()
  console.log(aa);  //1 global if var is not declared above the value will be 44
Copy the code

On the treatment of the same name

If the name is repeated during the promotion phase, it will not be redeclared, but will be redefined (subsequent assignments will replace previous assignments).

Fn =(0x001)=(0x002)=(0x003)=(0x004
fn() / / = > 4
function fn(){ console.log(1)} //(0x001)
fn() / / = > 4
function fn(){ console.log(2)} //(0x002)
fn()  / / = > 4
var fn = 13   // => fn=13
fn() // fn is not a function
function fn(){ console.log(3)} //(0x003)
fn() 
function fn(){ console.log(4)} //(0x004)
fn()
Copy the code

Function increase

Function is preferred

Every time a variable declaration of the var keyword is encountered, the system queries whether the name of the variable already exists in the current scope. If so, the declaration is ignored. If not, the variable declaration is promoted

Both variable declarations and function declarations are promoted, so in the case of repeated declarations

Pre-parsed functions are promoted first, then variables.

fn(); / / 1
var fn; 
function fn() { console.log(1); } 
var fn = function() { console.log(2); } 
fn(); / / 2
Copy the code

Although the var fn; Function fn (){… }, but since the function is promoted first, the var declaration of the same name is ignored. Although the var declaration of the same name is ignored, subsequent function declarations can override the previous one.

Ascending only improves the function declaration, not the function expression.

console.log(foo1); // [Function: foo1]
foo1(); // foo1
console.log(foo2); // undefined
foo2(); // TypeError: foo2 is not a function
function foo1 () {
	console.log("foo1");
};
var foo2 = function () {
	console.log("foo2");
}
// There are some questions here. Foo2 will report an error, isn't that also a declaration?
// foo2 is a function expression here and will not be promoted
Copy the code

A function promotion case

var a = 1;
function foo() {
    a = 10;
    console.log(a);
    return;
    function a() {};
}
foo();
console.log(a);
Copy the code
var a = 1; // define a global variable a
function foo() {
    Function a () {} to the top of the function scope
    Function a () {} = function() {}; The final form is as follows
    var a = function () {}; // Define and assign the local variable a.
    a = 10; // Changing the value of local variable A does not affect global variable A
    console.log(a); // Prints the value of local variable A: 10
    return;
}
foo();
console.log(a); // Prints the value of global variable A: 1
Copy the code

Temporary dead zone

ES6 explicitly states that if variables declared by let and const are present in a code block ({}), the scope of those variables is limited to the code block, that is, block-level scope

 console.log(a); //undefined
 var a = 1;
 console.log(b); // Error Cannot access 'b' before initialization
 let b = 1;
Copy the code
var a = 1; 
if(true){ 
    a = 2; 
    console.log(a); / /??
    leta; If it isvarAnd what is the result?console.log(a);  / /??
Copy the code
var a = 1;
if(true) {// If is added for a block-level scope and to read global a
// Dead zone start --------------------------
// Access to a will generate an error, cannot be used before the declaration
a = 2; 
console.log(a); 
/ / end of the dead zone -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- here before an error code will not perform the let down \ const must first statement is in use
// This is the usual way
let a;  // If this is var, the variable will be promoted to global
console.log(a); // undefined 
a = 3; 
console.log(a); / / 3
}
console.log(a); //1 If it is var a, the value is changed to 3
Copy the code

Let and const also “promote”, but unlike var, they are not assigned undefined by default and are prohibited from being used until they are declared. This is known as a temporary dead zone.

In summary: let const must be declared before being used

Initial understanding of execution context, scope chains

Global variables and functions defined by var become properties and methods of the Window object. Top-level declarations created by lets and const are not defined in the global context, but the effect of scope chain parsing is the same.

The context is destroyed when all of its code has been executed, including all variables and functions defined on it (the global context is destroyed when the application exits, such as closing the web page and exiting the browser).

The scope chain

Function execution forms a private scope (protecting private variables) to enter the private scope. First the variable is promoted (declared variables are private) and then the code is executed

  1. If the variable is private, treat it as private
  2. If the variable is not private, query up until the window global scope is calledThe scope chain
  • If the parent scope does not have this variable (even if the parent scope does not have this variable) : if the parent scope does not have this variable, the value of the variable = is equivalent to setting the property for the window and then operating on the window
 console.log(x, y); // undefined x 2
 var x = 10, 
     y = 20; // x = 10; y=20
 function fn() {
    // open up heap memory to form a private scope
    Var x (private variable)
    console.log(x, y); // if x is undefined and y is 20
    var x = y = 100; // x =100 (private) y =100
    console.log(x, y); / / 100 100
   }
 fn();
 console.log(x, y); / / 10, 100
Copy the code