Let the keyword

It works the same as Var

letK;let b,c,d
/ / value person
let e=100
Copy the code

Let declares the properties of variables

  1. Variables may not be declared repeatedly to prevent variable name contamination

    let star='millet'
    let star='Ming'
    Copy the code
  2. Block-level scope, valid only within a code block, but not outside a code block

    {
        let girl='cui flower'
    }
    console.log(girl)
    Copy the code
  3. There is no variable promotion

    console.log(obj)
    let obj=123131
    Copy the code
  4. The scope chain is not affected

    <body>
      <div class="container">
        <h2 class="page-header">I'm gonna switch colors</h2>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
      </div>
      <script>
        // Get the element
        let item = document.querySelectorAll('.item')
    
        // Loop through and bind events
        for (let i = 0; i < item.length; i++) {
          item[i].onclick = function () {
            // Change the background color of the current element
            // this.style.background = 'pink'
            item[i].style.background = 'pink'}} {let i = 0
        }
        console.log(i); {
          let i = 1
        } {
          let i = 2
        }
      </script>
    </body>
    Copy the code

    Const constants

    features

    1. Always assign initial values

      const A
      
      / / an error
      //Uncaught SyntaxError: Missing initializer in const declaration
      Copy the code
    2. Use uppercase for general constants (unspoken)

      const a=100
      Copy the code
    3. The value of a constant cannot be modified

      const a= 100
      const a=123
      
      'Uncaught SyntaxError: Identifier "a" has already been declared'
      Copy the code
    4. Block-level scope

      {
          const PLYER='UZI'
      }
      console.log(PLYER)
      
      Error: Uncaught ReferenceError: PLYER is not defined'
      Copy the code
    5. Changes to numbers and elements of objects do not count as changes to constants, and no error is reported

      If an element has changed without changing its address, no error is reportedconst TEAM=['UZI'.'MXLG'.'MINF'.'LETTme']
      
      TeAM=100 / / complains
      Copy the code

Structural assignment of variables

ES6 allows you to extract values from arrays and objects and assign values to variables in a certain pattern. It’s called “deconstructive assignment”

1. Array structure

const F4=['Little Shenyang'.'liu can'.'zhao four'.Song Xiao Bao]
let [xiao,liu,zhao,song]=F4
console.log(xiao,liu,zhao,song)
Copy the code

2. The structure of the object

const zhao ={
    name:"Zhao Benshan".age:'not'.xiaopin:function(){
        console.log('Skits')}}let {name,age,xiaopin}=zhao
Copy the code

ES6 simplified object writing

In ES6, it is allowed to write variables and functions as properties and methods of objects directly inside curly braces

This way of writing is more concise

let name='Dark Horse Programmer'
let change=function(){
    console.log('We can change you')}constSchool = {name change,improve(){
        console.log('We can make your code cleaner.')}}Copy the code

Arrow function in ES6

ES6 allows functions to be defined using [arrow](=>)

Application scenarios of arrow functions

Arrow functions are suitable for this – independent callbacks, timers, and array method callbacks

/ / before
let  fn=function(){console.log('before the ES6')}
let fun=(a,b) = >{
    console.log('after the ES6')
    return a+b
}
let result=fun(1.2)
console.log(result)
Copy the code

Note:

1. This is static. This always refers to the value of this in the scope in which the function was declared

function getName(){
    console.log(this.name)
}
let gerName2=() = >{
    console.log(this.name)
}

window.name='Dark Horse Programmer'
const school={
    name:'ATFUIFU'
}

// Call directly
getName()
getName2()

// Use the call method
getName.call(school)
getName2.call(school)
Copy the code

2. Cannot be used as a construct instantiation object

let Person=(name,age) = >{
    this.name=name
    this.age=age
}
let me= new Person('xiao'.40)
console.log(me)

/ / an error
'Uncaught TypeError: Person is not a constructor'
Copy the code

The arguments variable cannot be used

let fn=() = >{
    console.log(arguments)
}
fn(1.2.3)

/ / an error
'Uncaught ReferenceError: arguments is not defined'
Copy the code

4. Shorthand for arrow function

  1. Omit the parentheses when there is only one parameter

    let add=n= >{
        return n+n
    }
    console.log(add(9))
    Copy the code
  2. The return must be omitted if the code body contains only one statement, and the result of the statement execution is the return value of the function

let pow=(n) = >return n*n
console.log(pow(9))
Copy the code

Arrow functions are suitable for this – independent callbacks, timers, and array method callbacks

1 / / instance

 // Demand 1 click dib 2s after color change
    let ad = document.getElementById('ad')
    // Bind the event
    ad.addEventListener('click'.function () {
      // Save the value of this before ES6
      let _this = this;
      / / timer
      // setInterval(function () {
      // // Change background color this Cannot find the current this
      // // console.log(_this)
      // }, 2000)
      setInterval(() = > {
        // This refers to this in function
        this.style.background = "skyblue"
      }, 2000)})2 / / instance
 // Requirement 2 returns an even number of elements from an array
    const arr = [1.2.60.34.45.5.100]
    const result = arr.filter(function (item) {
      if (item % 2= = =0) {
        return true
      } else {
        return false}})const result = arr.filter(item= > item % 2= = =0)
    // The arrow function is suitable for this independent callback, timer, array method callback
Copy the code

In ES6, function arguments are assigned initial values

1. Initial value of parameter

function add(a,b,c=10){
    return a+b+c
}
let result=add(1.2)
console.log(result)
Copy the code

2. Use in combination with deconstructive assignment

function connect({host='127.0.0.1',username,password,port}){
    console.log(host)
    console.log(username)
    console.log(password)
    console.log(port)
}
connect({
    host:'loaclhost'.username:'root'.password:123456.port:3306
})
Copy the code

Rest parameters

Rest arguments are introduced in ES6 to get the arguments to a function, using arguments instead

// How ES5 gets arguments
function date(){
    console.log(arguments)
}
date(1.2.3.45.6.7.7.8)

/ / / rest parameters
function date(. args){
    console.log(args)
}
console.log(1.3.4.5.6.7.8)
Copy the code

Extension operator

concept

[…]. The extension operator converts an array to a comma-separated sequence of arguments

The extension operator is placed at the argument position, and the REST parameter is placed at the parameter position

const tfboys=['Yi Yangqian Seal'.'Wang Junkai'.'hanah']  // Convert to =>' yi Yangqianxi ',' Wang Junkai ',' Wang Yuan '

// Declare a function
function chuwan(){
    console.log(arguments) } chunwan(... tfboys)// Chunwan (' Yi Yangqianxi ',' Wang Junkai ',' Wang Yuan ')
Copy the code

Application of extension operators

  1. Array merge

    const kuaizi=['Wang Taili'."Xiao"]
    const fanghuang=['chenrui'.'ling flowers']
    
    const zuixuanxiaopingguo=kuaizi.concat(fenghuang)
    const zuixuanxiaopingguo=[...kuaizi,...fenghuang]
    console.log(zuixuanxiaopingguo)
    Copy the code
  2. Array cloning

    const sanhihua=['E'.'G'.'M']
    const sanyecai=[...sanzhihua]  //['E','G','M']
    console.log(sanyecai)
    Copy the code
  3. Turns a pseudo-array into a regular array

    <div></div>
    <div></div>
    <div></div>
    
    <script>
    const divs=document.querySelectorAll('div')
    const divArr=[...divs]
    console.log(divArr)
    </script>
    
    Copy the code

    Symbol

    concept

    ES6 introduced a new primitive data type, symbol, which represents unique values. It is the seventh data type of the JavaScript language and is a string-like data type

    The characteristics of the symbol

    1. The value of symbol is unique and is used to resolve name conflicts

    2. The symbol value cannot be manipulated with other data

    3. Object properties defined by symbol cannot use for.. In loops through, but you can use reflect.ownKeys to get all the key names of the object

    Create a symbol

    1. It can be used as a property name for an object, just strings andsymbolType can be used as a property name for an object
    2. No twosymbolThe values of theta are the same
    const symbol1 = Symbol(a);const symbol2 = Symbol(a); symbol1 === symbol2;// false
    
    const obj = {};
    obj[symbol1] = 'Hello';
    obj[symbol2] = 'World';
    
    obj[symbol1]; // 'Hello'
    obj[symbol2]; // 'World'
    Copy the code

    Although calling Symbol() makes it look like an object, Symbol is actually a primitive JavaScript data type. Using new using Symbol as the constructor causes an error.

    const symbol1 = Symbol(a);typeof symbol1; // 'symbol'
    symbol1 instanceof Object; // false
    
    // Throws "TypeError: Symbol is not a constructor"
    new Symbol(a);Copy the code

Private property

Since any two symbols are not equal, it is easy to simulate private properties in JavaScript. Symbol will not appear in the Object. The keys () in the results, so unless you explicitly export a symbol, or use the Object. The getOwnPropertySymbols () function to obtain, other code won’t be able to access this property.

function getObj() {
  const symbol = Symbol('test');
  const obj = {};
  obj[symbol] = 'test';
  return obj;
}

const obj = getObj();

Object.keys(obj); / / []

// This attribute cannot be accessed unless there is a reference to the symbol
obj[Symbol('test')]; // undefined

// Use getOwnPropertySymbols() to still get a reference to the symbol
const [symbol] = Object.getOwnPropertySymbols(obj);
obj[symbol]; // 'test'
Copy the code

Another reason is that symbol does not appear in the result of json.stringify (). Specifically, json.stringify () ignores the symbol property name and value:

const symbol = Symbol('test');
const obj = { [symbol]: 'test'.test: symbol };

JSON.stringify(obj); / / "{}"
Copy the code

Using Symbol to represent the internal state of an object is a good way to isolate user data from program state. With this, we no longer need some naming conventions, such as starting internal properties with ‘$’. The next time you need to define a private property

Template string

Before ES6 we usually used \ and + to create template strings

$("body").html("This demonstrates the output of HTML \
content to the page, including student's\
" + name + "," + seatNumber + "," + sex + " and so on.");
Copy the code

And for ES6

  • Basic string formatting, where expressions are embedded in strings for concatenation. Use ${} to set
  • ES6directlyUse backquotes (‘ ‘)
$("body").html(`This demonstrates the output of HTML content to the page, 
including student's ${name}.${seatNumber}.${sex} and so on.`);
Copy the code

Binary and octal literals

ES6 supports binary and octal literals, which can be converted to octal values by prefixing a number with an 0o or 0o:

let oValue = 0o10;
console.log(oValue); / / 8
 
let bValue = 0b10; // Binary uses' 0b 'or' 0b '
console.log(bValue); / / 2
Copy the code

for… Of and the for… in

for… Of is used to iterate over an iterator, such as a set of numbers:

let letters = ['a'.'b'.'c'];
letters.size = 3;
for (let letter of letters) {
  console.log(letter);
}
A, B, C
Copy the code

for… In is used to traverse properties in an object:

 let stus = ["Sam"."22"."Male"];
 for (let stu in stus) {
   console.log(stus[stu]);
  }
// Result: Sam, 22, male
Copy the code

ES6 classes in the

The class syntax is supported in ES6. However, ES6’s class is not a new object inheritance model; it is just a syntactic sugar representation of the prototype chain.

Use the static keyword in a function to define the methods and properties of the constructor:

class Student {
  constructor() {
    console.log("I'm a student.");
  }
 
  study() {
    console.log('study! ');
  }
 
  static read() {
    console.log("Reading Now."); }}console.log(typeof Student); // function
let stu = new Student(); // "I'm a student."
stu.study(); // "study!"
stu.read(); // "Reading Now."
Copy the code

Class inheritance and supersets:

class Phone {
  constructor() {
    console.log("I'm a phone."); }}class MI extends Phone {
  constructor() {
    super(a);console.log("I'm a phone designed by xiaomi"); }}let mi8 = new MI();
Copy the code

Extends allows a subclass to inherit from its parent class. Note that the constructor function of the subclass requires the super() function to be executed. Of course, you can also call a superclass method in a subclass method, such as super.parentMethodName().

A few points to note:

  • The declaration of a class does not promote(hoisting)If you’re going to use somethingClass, you must define it before you use it, otherwise one will be thrownReferenceErrorThe error
  • You do not need to use it to define a function in a classfunctionkeywords

Promise

Promises provide a new approach to asynchronous programming, treating future values as first-class objects, and they are already supported in many front-end libraries.

function timeout(duration = 0) {
    return new Promise((resolve, reject) = > {
        setTimeout(resolve, duration); })}var p = timeout(1000).then(() = > {
    return timeout(2000);
}).then(() = > {
    throw new Error("hmm");
}).catch(err= > {
    return Promise.all([timeout(100), timeout(200)]);
})

//11. Object literal shorthand
let type = 'quartz';
let color = 'rose';
let carat = 21.29;

const gemstone = {
  type: type,
  color: color,
  carat: carat
};

console.log(gemstone);

Copy the code

New data destruct Map, Set

These are new collection types that provide a much easier way to get the value of a property instead of using hasOwnProperty to check whether a property belongs to the stereotype chain or to the current object. At the same time, there are special get, ‘ ‘set’ methods for adding and retrieving property values.

//Sets
var a = new Set(a); a.add("hello").add("world").add("hello");
a.size===2
a.has('hello') = = =true
//Maps
var b= new Map(a); b.set("hello".42);
b.set(s, 34);
b.get(s) == 34;

Copy the code

The Generator Generator

role

  • The generator can be used to simulate synchronization. The essence of the generator is still call-back asynchron. That is, you still have to write asynchronous programs in an asynchronous way, but you can express them in a synchronous way.

  • The generator is not specifically designed to simulate synchronization, but to process multiple logical flows, that is, to simulate concurrency.

Simple to use

function* showWords() {
    yield 'one';
    yield 'two';
    return 'three';
}

var show = showWords();

show.next() // {done: false, value: "one"}
show.next() // {done: false, value: "two"}
show.next() // {done: true, value: "three"}
show.next() // {done: true, value: undefined}
Copy the code

Handles asynchrony, generates queues, can be applied to Ajax multi-layer nesting, etc

function fn1(){
    setTimeout(function(){
        console.log('fn1')
        g.next();
    },1000)}function fn2(){
    setTimeout(function(){
        console.log('fn2')
        g.next();
    },1000)}function fn3(){
    setTimeout(function(){
        console.log('fn3')
        g.next();
    },1000)}function* gen(){
    yield  fn1();
    yield  fn2();
    yield  fn3();
    return;
}
var g=gen();
g.next();
Copy the code

The difference between phi and a general function is phi and phi

(1) an asterisk (*) exists between function name and function name. (2) Have yield expressions inside the function body. Yield is the pause flag. A call to a Generator function does not execute immediately and does not return the result of the function’s run. Instead, it returns a pointer object to the internal state. That is, the traverser object. It is only when the next() method is called that the pointer is changed to the next state.