es6 review notes

I have seen it once before and review it again.
Here we mainly record some error prone points. For details, please refer to Rookie tutorial

const and let

1. temporary dead zone:

var PI = "a";
if(true){
  console.log(PI);  // ReferenceError: PI is not defined
  const PI = "3.1415926";
}

ES6 clearly stipulates that if there is a let or const in the code block, the variables declared by the code block for these commands will form a closed scope from the beginning of the block. In the code block, using the variable PI before declaring it will report an error.

2. no variable lifting

console.log(a);  //ReferenceError: a is not defined
let a = "apple";
 
console.log(b);  //undefined
var b = "banana";

3. global variables of let and var

The global scope variable declared with the var keyword belongs to the window object:

var carName = "Volvo";
// You can use window Carname access variable

The global scope variable declared with the let keyword does not belong to the window object:

let carName = "Volvo";
// Cannot use window Carname access variable

To sum up, let and const will be closed in the code block;

deconstruction

1. object deconstruction

basic

let { baz : foo } = { baz : 'ddd' };
// foo = 'ddd'

Residual operator deconstruction

let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40};
// a = 10
// b = 20
// rest = {c: 30, d: 40}

Symbol

1. as a unique attribute

When the Symbol value is used as the attribute name, the attribute is public rather than private and can be accessed outside the class. But it will not appear in for In, for Of will not be used by object Keys(), object Getownpropertynames() returns.

2. as a constant

Such as enumeration

3. single instance mode

Symbol.for()
Symbol.keyFor()

Map and Set

1.map iteration

var myMap = new Map();
myMap.set(0, "zero");
myMap.set(1, "one");
 
// Two log s will be displayed. One is "0 = zero" and the other is "1 = one"
for (var [key, value] of myMap) {
  console.log(key + " = " + value);
}
for (var [key, value] of myMap.entries()) {
  console.log(key + " = " + value);
}
/* The entries method returns a new Iterator object, which contains the [key, value] array of each element in the Map object in the insertion order. */
 
// Two log s will be displayed. One is' 0 'and the other is' 1'
for (var key of myMap.keys()) {
  console.log(key);
}
/* The keys method returns a new Iterator object that contains the keys of each element in the Map object in the order of insertion. */
 
// Two log s will be displayed. One is "zero" and the other is "one"
for (var value of myMap.values()) {
  console.log(value);
}
/* The values method returns a new Iterator object that contains the values of each element in the Map object in the order of insertion. */

2.map operation

Array conversion, cloning, merging

3.set

Array de duplication, union, intersection, subtraction

Reflect and Proxy

Proxy can intercept operations such as reading and function calling of the target object, and then perform operation processing. It does not directly operate on objects, but, like the proxy mode, operates through the proxy objects of objects. During these operations, you can add some required additional operations.

Reflect can be used to obtain the behavior of the target Object. It is similar to Object, but it is easier to read and provides a more elegant way to manipulate objects. Its method corresponds to Proxy.

ES6 string

1. insert function

function f(){
  return "have fun!";
}
let string2= `Game start,${f()}`;
console.log(string2);  // Game start,have fun!

2. label template

A label template is a function call whose parameter is a template string.

alert`Hello world!`;
// Equivalent to
alert('Hello world!');

numerical value

Binary, octal 0b\0o

constant

New method:

as

Math.trunc
 Used to return the integer part of a number.

Math.trunc(12.3); // 12
Math.trunc(12);   // 12

Exponential operator

1 ** 2; // 1
// Right combination, calculated from right to left
2 ** 2 ** 3; // 256
// **=
let exam = 2;
exam ** = 2; // 4

object

1. attribute name expression

const hello = "Hello";
const obj = {
 [hello]
};
obj  //SyntaxError: Unexpected token }
 
const hello = "Hello";
const obj = {
 [hello+"2"]:"world"
};
obj  //{Hello2: "world"}

2.Object.is(value1, value2)

It is used to compare whether two values are strictly equal. It is basically similar to (=).
Difference from (=)

//First, +0 is not equal to -0
Object.is(+0,-0);  //false
+0 === -0  //true
//Second, NaN equals itself
Object.is(NaN,NaN); //true
NaN === NaN  //false

array

Array.of()

Form an array of all values in the parameter as elements.

console.log(Array.of(1, 2, 3, 4)); // [1, 2, 3, 4]

Array.from()

Converts a class array object or an iteratable object to an array.

// The parameter is an array, which returns the same array as the original array
console.log(Array.from([1, 2])); // [1, 2]

Convert iteratible objects

Transform map

let map = new Map();
map.set('key0', 'value0');
map.set('key1', 'value1');
console.log(Array.from(map)); // [['key0', 'value0'],['key1',
// 'value1']]

view

Views are interfaces for manipulating memory.

The view can manipulate array buffers or a subset of buffer bytes and read and write data according to one of the numeric data types.

The DataView type is a generic array buffer view that supports all eight numeric data types.

Create:

// The default DataView can manipulate the entire contents of the array buffer
let buffer = new ArrayBuffer(10);
    dataView = new DataView(buffer); 
dataView.setInt8(0,1);
console.log(dataView.getInt8(0)); // 1

Array operations have always been the focus

function

Arrow function

The this object in the arrow function body is the object when defining the function, not the object when using the function.
Before ES6, this object in JavaScript has always been very popular. For callback functions, you often see code like var self = this. In order to pass external this to the callback function, you don't need to do this with the arrow function. Just use this.

Suitable scenarios

// Callback function
var Person = {
    'age': 18,
    'sayHello': function () {
      setTimeout(function () {
        console.log(this.age);
      });
    }
};
var age = 20;
Person.sayHello();  // 20
 
var Person1 = {
    'age': 18,
    'sayHello': function () {
      setTimeout(()=>{
        console.log(this.age);
      });
    }
};
var age = 20;
Person1.sayHello();  // 18

Therefore, when we need to maintain a this context, we can use the arrow function.

Unsuitable scenarios

Defines a method of a function that contains this

var Person = {
    'age': 18,
    'sayHello': ()=>{
        console.log(this.age);
      }
};
var age = 20;
Person.sayHello();  // 20
// this refers to the global object
 
var Person1 = {
    'age': 18,
    'sayHello': function () {
        console.log(this.age);
    }
};
var age = 20;
Person1.sayHello();   // 18
// this point to the Person1 object
 Need dynamic this When

var button = document.getElementById('userClick');
button.addEventListener('click', () => {
     this.classList.toggle('on');
});

Button's listening function is an arrow function, so this in the listening function refers to the outer this object at the time of definition, that is, Window, which makes it impossible to operate on the clicked button object.

iterator

const items = ["zero", "one", "two"];
const it = items[Symbol.iterator]();
 
it.next();
>{value: "zero", done: false}
it.next();
>{value: "one", done: false}
it.next();
>{value: "two", done: false}
it.next();
>{value: undefined, done: true}

let, const, and var for Of

If let and const are used, each iteration will create a new storage space, which can ensure that the scope is within the iteration.

const nums = ["zero", "one", "two"];
 
for (const num of nums) {
  console.log(num);
}
// Report ReferenceError
console.log(num);

From the above example, we can see that the last sentence will report an exception. The reason is that the scope of num is only inside the loop body, and it is invalid outside. For details, please refer to the let and const chapters. With VaR, the above situation will not occur, because var will act on the global, and the iteration will not create a new storage space every time.

Class

The essence of class is function.

Instance attribute: the attribute defined on the instance object (this).

class Example {
    a = 2;
    constructor () {
        console.log(this.a);
    }
}

Constructor

class Test {
    constructor(){
        // Returns the instance object this by default
    }
}
console.log(new Test() instanceof Test); // true
 
class Example {
    constructor(){
        // Specify return object
        return new Test();
    }
}
console.log(new Example() instanceof Example); // false

Decorator

Skip

getter and setter must appear at the same level

inherit

class Child2 extends Father {
    constructor(){
        super();
        // Call the normal method of the parent class
        console.log(super.test()); // 0
    }
    static test3(){
        // Calling a parent class static method
        return super.test1+2;
    }
}
Child2.test3(); // 3

ES6 module

The module can import and export various types of variables, such as functions, objects, strings, numbers, Boolean values, classes, etc.

Each module has its own context. The variables declared in each module are local variables and will not pollute the global scope.

Each module is loaded only once (it is a singleton). If you load the same file in the same directory, you can read it directly from memory.

Note that the module is singleton

ES6 Generator function

Skip

async/await

Skip

Tags: Javascript

Posted by geetakhurana on Tue, 31 May 2022 17:01:09 +0530