Review of JS foundation and practice of ES6 new grammar

Posted by aquarius on Fri, 25 Feb 2022 16:48:32 +0100

This series follows the video "Shangsi Valley Web front end ES6 tutorial, covering ES6-ES11" from station B and summarizes the relevant JS basic, advanced and ES6 new syntax

let declaration variable

let is a new variable declaration keyword in ES6. The syntax is similar to the previous var, but it is different in characteristics and details.

let a;
let b,c,d;
let e = 100;
let f = 521,g = 'i love u',h = [];

console.log(a,b,c,d,e,f,g,h)

Properties of the let keyword

1. Variables cannot be declared repeatedly

let a = 12;
let a = 34;

The above code will report an error after running, but it will not report an error if using VaR in the past. This also represents the advantage of let keyword over var.

2. Block level scope

There are three scopes in ES5: global scope, function scope and eval scope.
ES6 introduces a new block level scope.
Block level scope actually means that the variables in the code block only work in the code block and are invalid outside the code block.

{
    let a = 12;
}
console.log(a);

The above code will report the following error.

If let is changed to var, the above code will not report an error, because var has no block level scope.

The variable declared by ES5 var keyword is a variable with the same name directly hung on the window:

{
   var a = 12;
}
console.log(window.a);//Equivalent to console log(a)

If it is function, the situation is different. Because the variable of var has function scope, the following code will report an error.

function fn1(){
    var a = 1
}
console.log(a)

3. There is no "variable promotion"

The variable and function names declared by var keyword in ES5 will be resolved and opened up memory in advance, and given the initial value undefined.

console.log(a)
var a = 12;

The above code outputs the following results:

It is equivalent to:

var a;//The system automatically assigns the initial value undefined to the variable if it is declared without assignment
console.log(a)
a = 12;

The let keyword does not exist in this case, which can be understood as that let is more strict than var.

console.log(a)
let a = 12;

The above code will report the following error:

4. It does not affect the scope chain

When another function is declared inside a function, the effect of function nesting will appear. When the function is nested, the inner function can only be executed within the scope of the outer function. During the execution of the inner function, if a variable needs to be introduced, it will first look in the current scope. If it is not found, it will continue to look in the scope of the upper level until the global scope. We call this chained query relationship scope chain.

{
    let a = 12;
    function fn(){
        console.log(a);
    }
    fn();
}

The above code, console Log (a) did not find the declaration of a in its block level scope, but found the definition of a in the upper level scope.

Comprehensive example

To achieve the following effects, 3 DIV, click to change the background color.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .item{
            width: 100px;height: 30px;
            border: 1px solid #ccc;
            float: left;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2 class="page-header">Click to switch colors</h2>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
    </div>
<script>
let items = document.getElementsByClassName("item");
for(let i=0;i<items.length;i++){
    items[i].onclick = function(){
        items[i].style.backgroundColor = "pink"
    }
}
</script>
    
</body>
</html>

Here, in fact, we have adopted the final successful code.

let items = document.getElementsByClassName("item");
for(let i=0;i<items.length;i++){
    items[i].onclick = function(){
        items[i].style.backgroundColor = "pink"
    }
}

However, according to the previous writing, the following two versions will appear:

var items = document.getElementsByClassName("item");
for(var i=0;i<items.length;i++){
    items[i].onclick = function(){
        this.style.backgroundColor = "pink"
    }
}

The above version can run normally, while the following version will report an error.

var items = document.getElementsByClassName("item");
for(var i=0;i<items.length;i++){
    items[i].onclick = function(){
        items[i].style.backgroundColor = "pink"
    }
}

This involves the problem of this pointing and the promotion of var variables.
As mentioned earlier, the variable declared by var will mount a variable with the same name on window.
The above for statement is executed globally, so the variable I declared by var will be attached to window and become window i.
The for statement is executed three times. First bind the onclick event processing from items[0] to items[2]. At this time, window I has been equal to 3;
No matter which div we click, that is, items[i], I is equal to 3, and if items[3] does not exist, an error will be reported.

The solution is to use let.

const declaration constant

const PI = 3.1415926
console.log(PI)
  • Constants must be given initial values
  • Constant names should preferably be all uppercase (not mandatory)
  • Constant cannot modify value
  • Constants are also block level scopes
  • The modification of array and object elements is not a modification of constants

Deconstruction and assignment of variables

Deconstruction assignment of array

const people = ["Zhang San","Li Si","Wang Wu","Pockmarks"]
let [zhang,li,wang,ma] = people

console.log(zhang,li,wang,ma)

Deconstruction assignment of object

const zhang = {
    name:"Zhang San",
    age:30,
    run:function(){
        console.log("Abscond from crime")
    }
}

let {name,age,run}
console.log(name,age)
run()

Template string

In ES5, there are only two string forms: single quotation mark and double quotation mark. In ES6, a new string marking symbol, ` ` is introduced, that is, the symbol of inline code in Markdown.

let str = `I am also a string`
console.log(str,typeof str)


Template strings have many new features that previous strings do not have:

  • It can wrap lines directly, carry multiple lines of text, and inherit the syntax characteristics of the original JS, that is, ignore redundant spaces
  • You can directly replace template variables.
let str = `Me too
          String`
document.write(str)
let name = "Zhang San"
let str = `${name}Welcome!`
document.write(str)

Arrow function

set

map

class

modularization

export and import

Is require() the command of NodeJS?

export and import
1.js

export let a = 12;

export function fn1(){
    console.log("This is ES6 Functions in modules")
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<script type="module">
    import * as m1 from "./1.js"
    console.log(m1)
</script>
    
</body>
</html>

The actual test will report an error.

According to< Using es6 modularization, Access to script at 'file: / / /... from origin' null 'has been blocked... Error The explanation of the article is that cross domain problems have occurred. The solution is to build a local server, such as NodeJS.

Unified exposure method

let a = 12;

function fn1(){
    console.log("This is ES6 Functions in modules")
}

export{a,fn1}

Default exposure

export default{
    a:12,
    fn1:function(){
        console.log("fn1")
    }
}

Topics: Javascript Front-end