Software engineers, learn the new features of JavaScript ES6

overview

        As a software engineer, whether you are a front-end development position or not, you will use a little JavaScript in your work more or less. JavaScript is a well-known language name, but this language name is a registered trademark of Oracle Corporation. The official name of JavaScript is ECMAScript. In November 1996, Netscape, the creator of JavaScript, submitted JS to the international standards organization ECMA (European Computer Manufacturers Association), hoping that this language could become an international standard. Subsequently, ECMA released the standard for specifying the browser scripting language, namely ECMAScript, which is also conducive to the openness and neutrality of this language.

        ES6, the full name of ECMAScript 6.0, officially known as ECMAScript 2015, is the next version of JavaScript standard, which was released on June 17, 2015.

        Let's understand the development process of ECMAScript.

        In 1997, ECMAScript 1.0 was born.

        In June 1998, ECMAScript 2.0 was born, including some minor changes to synchronize the independent ISO international standard.

        In December 1999, ECMAScript 3.0 was born and has been widely supported in the industry. It laid the basic syntax of JS.

        ECMAScript 4.0 in 2000 was the predecessor of ES6, but because this version was too drastic, it was temporarily "harmonized".

        In December 2009, ECMAScript version 5.0 was officially released. The ECMA expert group expects the fifth edition of ECMAScript to be the mainstream development standard from mid-2013 to 2018. In June 2011, ES version 5.1 was released and became an ISO international standard.

        In 2013, the ES6 draft was frozen, no new features will be added, and new features will be put into ES7.

        In June 2015, ES6 was officially passed and became an international standard.

        JavaScript ES6 proposes many new features, and its goal is to make JavaScript language can be used to write complex large-scale applications and become an enterprise-level development language.

        let keyword

        let is used to declare local variables, which is block-level scope. After the definition of let is used inside the function, it has no effect on the outside of the function, and there is a temporary dead zone constraint.

{ 
    let i = 9;
}
// 提示找不到i的错误 
console.log(i);

let a = 99;            
f();
// 输出:99
console.log(a); 
function f() {
   // 提示找不到i的错误 
   console.log(a); 
   let a = 10;
   // 输出:10
   console.log(a);
}

const keyword

        const is used to declare constants, variables defined with it cannot be modified, and must be initialized. The value of a constant cannot be changed by reassignment, and it cannot be redeclared.

const foo = {};

foo.prop = 123;
// 其属性可以修改,正常输出:123
console.log(foo.prop)

// 报错,const变量自身不可修改
foo = {};

export/import

        1. The members exposed by export default can be received by any variable. In a module, it can only be exposed once by using export default.

        2. Members exposed externally using export can only be received using {}, which is called on-demand export. Multiple exports can be used in a module at the same time. If you want to change the name when referencing, you can pass as.

// test.js
export default {
    name: 'zs',
    age: 10
};

export var title = "小星星";

//main.js
import m1, { title } from './test'

// test2.js
export var title = "小星星";
export var content = '哈哈哈';

// main2.js
import { title, content } from './test2'
import { title as title123, content } from './test2'
import * as test from './test2'

arrow function

        Arrow functions are equivalent to anonymous functions and simplify function definitions. Arrow functions have two formats: the first type contains only one expression, and even { ... } and return are omitted; the second type can contain multiple statements, and { ... } and return cannot be omitted at this time .

() => 3.14
var double = num => num * 2
(x, y) => x * x + y * y

        Unlike ordinary functions, arrow functions do not bind this, or arrow functions do not change the original binding of this. The this inside the arrow function is lexical scope, determined by the context.

var obj = {
    birth: 1990,
    getAge: function () {
        var b = this.birth; // 1990
        var fn = () => new Date().getFullYear() - this.birth;
        return fn();
    }
};

template string

        Template strings are marked with ` (backticks), and variables are enclosed in ${}. Template strings can introduce variables, backticks themselves, js expressions, and call functions. If template strings are used to represent multiline strings, all whitespace and indentation will be preserved in the output.

`He is <b>${person.name}</b>and we wish to know his${person.age}.that is all`

console.log( `No matter\` what you do,
      I trust you.`);

var x=88;
var y=100;
console.log(`x=${++x},y=${x+y}`);

function test() { return “I like ES6"; }
console.log(`hello, ${test()}`);

function with default parameters

        The default parameter function supports providing default values ​​for the parameters of the function, and the default parameters must be at the end of all parameters.

function greet(name = 'Student', greeting = 'Welcome') {
  return `${greeting} ${name}!`;
}

greet();
greet('James');
greet('Richard', 'Howdy');

to deconstruct

        Destructuring, for extracting values ​​from arrays and objects and assigning them to unique variables.

const point = [10, 25, -34];
const [x, y, z] = point;
console.log(x, y, z);

const gemstone = {
  type: 'quartz',
  color: 'rose',
  karat: 21.29
};
const {type, color, karat} = gemstone;
const {type2, color2, karat2} = gemstone;
console.log(type, color, karat);

...spread operator

        ..., used to serialize the array as a comma-separated sequence.

// 1、获取数组最大的值。
Math.max(...[1, 2, 3])

// 2、调用方法
function sum(a, b){
     console.log(a+b)
}
sum(...[2, 3])

// 3、连接数组
var arr1 = [0, 1, 2]; 
var arr2 = [3, 4, 5];  
arr1.push(...arr2);  

// 4、连接数组
var arr1 = ['a', 'b']; 
var arr2 = ['c']; 
[...arr1, ...arr2] 

// 5、字符串转为真正的数组
[...'hello']  // [ "h", "e", "l", "l", "o" ]  

// 6、扩展运算法
let map = new Map([ [1, 'one'], [2, 'two'] ]);  
let arr = [...map.keys()];

...residual arguments/varargs

        The remaining parameters, also denoted by three consecutive dots ( ... ), can bind a variable number of elements into an array.

        Variable parameters are used for functions whose parameters are not fixed. Before ES6, parameters objects (arguments) were used for processing.

// 剩余参数
const order = [20.17, 18.67, 1.50, "cheese", "eggs", "milk", "bread"];
const [total, subtotal, tax, ...items] = order;
console.log(total, subtotal, tax, items);

// 可变参数
function sum(...nums) {
     let total = 0;  
     for(const num of nums) {
            total += num;
     }
     return total;
}

Simpler Object Literals

        ES6 makes it easier to declare object literals, provides property shorthand and method shorthand functions, and new features of property name calculation.

function getInfo(name, age, weight) {
    return {
        name, age, weight,
        ['over' + weight]: true,
        desc() {
            console.log(name, age, weight);
        }
    };
}

let person = getInfo('Kia', 27, 400);
console.log(person);   // {name: "Kia", age: 27, weight: 400, over400: true, desc: ƒ}

for of

        for of supports terminating the loop and will not traverse non-numeric properties.

const fruits = ['apple','coconut','mango'];
fruits.fav = 'my favorite fruit';

for(let index in fruits){
    console.log(fruits[index]);
}

for(let fruit of fruits){
    if(fruit === 'mango' ){
        break;
    }
    console.log(fruit);
}

Map

        JavaScript's Object itself is a data structure of key-value pairs, but in fact, attributes and values ​​​​constitute "string-value" pairs, and attributes can only be strings. Map provides a data structure of "value-value" pairs, and the key name can be not only a string, but also an object. It is a more complete Hash structure.

const map1 = new Map();
const objkey = {p1: 'v1'};
map1.set(objkey, 'hello');
console.log(map1.get(objkey));
console.log('%s', map1.size);

const map2 = new Map();
map2.set('a', 4);
console.log('map2: %s', map2.has('a'));
map2.delete('a');
map2.clear();

for (let key of map2.keys()) {
  console.log(key);
}
for (let value of map2.values()) {
  console.log(value);
}
for (let item of map2.entries()) {
  console.log(item[0], item[1]);
}
for (let [key, value] of map2.entries()) {
  console.log(key, value);
}

kind

        Classes in ES6 are somewhat similar to classes in C++ and Java.

        1. To declare a class, first write the class keyword, followed by the name of the class. The syntax of other parts is similar to the shorthand form of the object literal method, but there is no need to use commas to separate the elements of the subclass.

        2. The constructor method is a construction method that is called when a class is instantiated. The constructor method is necessary and unique. A class cannot contain multiple constructor methods. We can customize some object properties in this method.

        3. The instance method of the class can be defined in the class, and the object can call this method after instantiation.

        4. The definition of a static method needs to be identified by the static keyword, but the instance method does not. Static methods are invoked through the class name, while instance methods are invoked through the instance object.

        5. Static attributes are written outside the class definition (ES7 has a new way of writing, just use static to write inside the class definition).

        6. You must use the new creation word to create an instance object of the class.

        7. You must declare the definition class before creating an instance, otherwise an error will be reported.

class Animal {
    constructor(name){
        this.name = name;
    }

    getName(){
        return 'This is a '+this.name;
    }

     static friends(a1,a2){
         return `${a1.name} and ${a2.name} are friends`;
     }
}

let dog = new Animal('dog');
console.log(dog.name);
console.log(dog.getName());

 let cat = new Animal('cat');
 Animal.friends(dog, cat);

inherit

        1. Use the extends keyword to realize that the subclass (derived class) inherits the parent class (base class). A method in a derived class always overrides a method of the same name in the base class.

        2. The keyword super is equivalent to this in the parent class. You can use super to refer to the parent class and access the methods of the parent class.

        3. The subclass must call the super method in the constructor method.

        4. In the constructor of the subclass, the super method must be called before this can be used, otherwise an error will be reported.

        5. To access the function of the parent class in the ordinary function (non-constructor) of the subclass, you can use this or super.

        6. To access the properties of the parent class in the subclass, you can only use this, not super.

        7. Support the inheritance of built-in objects.

class Animal {
      constructor(name){
          this.name = name;
      }

      say(){
          return `This is a animal`;
      }
}
  
class Dog extends Animal {
  constructor(name, color){
      super(name);
      this.color = color;
  }

  getDesc(){
      return `${super.say()},
              name:${this.name},
              color:${this.color}`;
  }
}

  let dog = new Dog("dog", "black");
  dog.getDesc();

Web Worker

        The significance of Web Worker is that it can strip some time-consuming data processing operations from the main thread, so that the main thread can focus more on page rendering and user interaction.

// main.js
let worker = new Worker('work.js');

worker.postMessage('Hello World');
worker.postMessage({method: 'echo', args: ['Work']});

worker.onmessage = function (event) {
  console.log('Recv msg ' + event.data);
}

worker.terminate();

// work.js
importScripts('script1.js');

self.onmessage = function (event) {
  console.log('You said: ' + event.data);
}

self.close();

Promise

        According to the Promise/A specification, promise is an object and only needs the then method. The then method takes the following three parameters: success callback, failure callback, and forward callback (the specification does not require the implementation of the forward callback, but many of them are implemented).

        A brand new promise object is returned from each then call.

        The Promise object represents an asynchronous operation, which is not affected by the outside world and has three states: Pending (in progress, unfinished), Resolved (completed, also known as Fulfilled), and Rejected (failed).

function getNumber(){
    var p = new Promise(function(resolve, reject){
        setTimeout(function(){
            var num = Math.ceil(Math.random()*10);
            if(num<=5){
                resolve(num);
            }
            else{
                reject('数字太大了');
            }
        }, 2000);
    });
    return p;            
}

getNumber()
.then(
    function(data){
        console.log('resolved');
        console.log(somedata);
}, 
    function(reason, data){
        console.log('rejected');
})
.catch(function(reason){
    console.log('rejected');
});

async/await

        1. async/await is a syntax proposed by ES7, which can be used in projects through babel.

        2. async/await is a solution to solve asynchronous problems with synchronous thinking (the code will continue to execute after the result comes out).

        3. async/await is more semantic, async is shorthand for "asynchronous", async function is used to declare that a function is asynchronous; await, which can be considered as shorthand for async wait, is used to wait for an asynchronous method to complete.

        4. The traditional callback nesting can be replaced by synchronous writing of multi-layer async function.

        5. async automatically converts regular functions into Promise, and the return value is also a Promise object.

        6. The callback function specified by the then method will be executed only after the asynchronous operation inside the async function is executed.

        7. Await can only be used inside an async function, and an error will be reported if it is used inside an ordinary function.

function timeout(ms) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {reject('error')}, ms);
  });
}

async function asyncPrint(ms) {
  try {
     console.log('start');
     await timeout(ms);
     console.log('end');
  } catch(err) {
     console.log(err);
  }
}

asyncPrint(1000);

async function asyncPrint2(ms) {
  console.log('start');
  await timeout(ms)
  console.log('end');
}

asyncPrint2(1000).catch(err => {
    console.log(err);
});

Guess you like

Origin blog.csdn.net/hope_wisdom/article/details/131615701