es6 Quick Start

Keywords: Javascript REST ECMAScript npm

es6 Quick Start

ES6 introduction

ECMAScript 6.0 (hereinafter referred to as ES6) is the next generation standard of JavaScript language, which was officially released in June 2015. Its goal is to enable JavaScript language to be used to write complex large-scale applications and to become an enterprise-level development language.

The relationship between ES6 and ECMAScript 2015

The first version of ES6 was released in June 2015. Its official name is "ECMAScript 2015 Standard" (ES2015). ES6 is not only a historical term, but also a general term. It means the next generation standard of JavaScript after version 5.1. It covers ES2015, ES2016, ES2017 and so on. ES2015 is the official name, especially the language standard of the official version released that year.

So, we can think of ES6 = ES2015

Babel

Because not all browsers are compatible with all the features of ES6 at present, the actual project still mainly has ES5 grammar to develop.

Here you can see how well es6 supports the browsers http://kangax.github.io/compat-table/es6/

But ES6 is the standard after all, and more and more projects have been developed with ES6. You need to understand the code written by other people, while letting others understand the code you write. The most important thing is if your sister asks you, what is ES6?

Babel is a widely used ES6 transcoder, which can convert ES6 code to ES5 code and execute in the existing environment. You can go to the official website to find out about it. https://babeljs.io/

What Babel does is simply parse the code written by ES6 grammar into ES5 grammar, so that all browsers can run normally.

For example:

// Before transcoding
input.map(item => item + 1);

// After transcoding
input.map(function (item) {
  return item + 1;
});

You can see online what it looks like to convert ES6 code into ES5 on the official babel website.

http://babeljs.io/repl/ Sometimes it's not very stable. You may need to turn it over ()

To use babel in a project, you need to configure the. babelrc file and store it in the project root directory.

Install bable-cli first

npm install babel-cli -g

Then install a plug-in that compiles es6 into es5

npm install --save-dev babel-preset-es2015

Add this configuration to.babelrc

{
    "presets": ["es2015"],
    "plugins": []
  }

Then run

babel es6.js -o es5.js

You can see that es5.js is the parsed script

babel has a large number of plug-ins, and you need to know them by yourself.

Common syntax

let,const

let

Let and const are similar to var. Let is a block-level scope declaration, and the variables declared are valid only within the block in which the let resides.

{
  let a = 10;
  var b = 1;
}

a // ReferenceError: a is not defined.
b // 1

The most typical example is the for loop

var a = [];
for (var i = 0; i < 10; i++) {
  a[i] = function () {
    console.log(i);
  };
}
a[6](); // 10

Often we need to use closure techniques to deal with it.

var a = [];
for (var i = 0; i < 10; i++) {
  (function(i){
    a[i] = function () {
    console.log(i);
    };
  })(i);
}
a[6]();  //6

It's much easier to switch to let.

var a = [];
for (let i = 0; i < 10; i++) {
  a[i] = function () {
    console.log(i);
  };
}
a[6](); // 6

Variable Lifting Problem

The var declaration has the problem of variable escalation. If the variable is used before the declaration, its value will output undefined. The let declaration changes this strange logic. The variables declared by the let must be declared first and then used, otherwise they will be wrong.

// The situation of var
console.log(foo); // undefined
var foo = 2;

// let situation
console.log(bar); // ReferenceError
let bar = 2;

No duplication of declarations

Unlike var, let does not allow the same variable to be declared repeatedly in the same scope.

// normal
function () {
  var a = 10;
  var a = 1;
}
// Report errors
function () {
  let a = 10;
  var a = 1;
}

// Report errors
function () {
  let a = 10;
  let a = 1;
}
const

const is used to declare a constant. Once declared, the value of a constant cannot be changed. And the assignment must be initialized immediately after declaration, not later.

//Report errors
const PI = 3.1415;
PI // 3.1415
PI = 3;

//Report errors
const DOMAIN;
DOMAIN = 'jd.com';

const and let are very similar: 1. They are only valid in block-level scope, 2. They do not promote variables, and 3. They cannot be redefined.

Although the variable declared by const cannot be changed, the const command only guarantees that the address of the assigned variable is unchanged, and does not guarantee that the data of the changed address is unchanged. Therefore, when the assigned variable is a value-referenced variable, you should be extra careful.

Class

The traditional method of JavaScript language is to define and generate new objects through constructors.

function Human(name) {
  this.name = name;
}

Human.prototype.sayName = function () {
  return '(My name is' + this.name + )';
};
var zhang3 = new Human('zhang3');
var li4 = new Human('li4');
var wang5 = new Human('wang5');

ES6 provides a closer approach to traditional languages (C++ and Java), introducing the concept of Class (class) as a template for objects. Classes can be defined by the class keyword. Essentially, ES6's class can be seen as a grammatical sugar. Most of its functions can be achieved by ES5. The new class writing just makes the object prototype more clear and more like the grammar of object-oriented programming. The above code is rewritten with the "class" of ES6, as follows.

class Human {
  constructor(name) {
    this.name = name;
  }
  sayName() {
    return '(My name is' + this.name + )';
  }
}

var zhang3 = new Human('zhang3');
var li4 = new Human('li4');
var wang5 = new Human('wang5');

constructor

The constructor method is the default method of the class, which is called automatically when the object instance is generated by the new command. A class must have constructor methods, and if there is no explicit definition, an empty constructor method will be added by default.

The constructor method returns the instance object (that is, this) by default, and can specify that another object be returned.

class Foo {
  constructor() {
    return Object.create(null);
  }
}

new Foo() instanceof Foo
// false

extends

Class es can be inherited through extends keywords, which is much clearer and more convenient than ES5 through modifying the prototype chain to achieve inheritance.

class Woman extends Human {
  constructor(name) {
    super(name); // Call the constructor(name) of the parent class;
    this.sex = 'female';
  }
}

let hanmeimei = new Woman('hanmeimei');

=>

Where functional expressions are needed, they can be replaced by =>, the code is concise, and this is bound.

// bad
[1, 2, 3].map(function (x) {
  return x * x;
});

// good
[1, 2, 3].map((x) => {
  return x * x;
});

// best
[1, 2, 3].map(x => x * x);

Arrow function replaces Function.prototype.bind

// bad
const self = this;
const boundMethod = function(...params) {
  return method.apply(self, params);
}

// acceptable
const boundMethod = method.bind(this);

// best
const boundMethod = (...params) => method.apply(this, params);

deconstruction

ES6 allows you to extract values from arrays and objects according to a certain pattern and assign variables, which is called Destructuring.

I don't understand. Shome the code.

Array deconstruction assignment

// before
let a = 1;
let b = 2;
let c = 3;
//after
let [a, b, c] = [1, 2, 3];
let [foo, [[bar], baz]] = [1, [[2], 3]];
let [ , , third] = ["foo", "bar", "baz"];

Object deconstruction assignment

let { foo, bar } = { foo: "aaa", bar: "bbb" };
let { bar, foo } = { foo: "aaa", bar: "bbb" };

//If the variable name is different from the attribute name, you can write it as follows
var { foo: baz } = { foo: 'aaa', bar: 'bbb' };

String deconstruction assignment

const [a, b, c, d, e] = 'hello';

It can also deconstruct and assign logarithmic and Boolean values and function parameters.

Set and Map

Set

ES6 provides a new data structure Set. It is similar to an array, but the values of members are unique and there are no duplicate values.

// Example 1
var set = new Set([1, 2, 3, 4, 4]);
[...set]
// [1, 2, 3, 4]

// Example two
var items = new Set([1, 2, 3, 4, 5, 5, 5, 5]);
items.size // 5

// Example three
function divs () {
  return [...document.querySelectorAll('div')];
}

var set = new Set(divs());
set.size // 56

// Be similar to
divs().forEach(div => set.add(div));
set.size // 56

Map

JavaScript objects are essentially sets of key-value pairs (Hash structures), but traditionally only strings are used as keys. This has brought great limitations to its use. To solve this problem, ES6 provides Map data structure. It is similar to an object and a collection of key-value pairs, but the scope of "keys" is not limited to strings. Various types of values (including objects) can be used as keys. That is to say, Object structure provides the correspondence of "string-value" and Map structure provides the correspondence of "value-value", which is a more perfect Hash structure implementation. Map is more appropriate than Object if you need a data structure of "key-value pairs".

var m = new Map();
var o = {p: 'Hello World'};

m.set(o, 'content')
m.get(o) // "content"

m.has(o) // true
m.delete(o) // true
m.has(o) // false

String template

In traditional JavaScript languages, output templates are usually written in this way.

$('#result').append(
  'There are <b>' + basket.count + '</b> ' +
  'items in your basket, ' +
  '<em>' + basket.onSale +
  '</em> are on sale!'
);

ES6 is solved in this way

$('#result').append(`
  There are <b>${basket.count}</b> items
   in your basket, <em>${basket.onSale}</em>
  are on sale!
`);

If a template string is used to represent a multi-line string, all spaces and indentations are retained in the output.

$('#list').html(`
<ul>
  <li>first</li>
  <li>second</li>
</ul>
`);

Variables can also be embedded in the string template, which can be written in ${}.

var x = 1;
var y = 2;

`${x} + ${y} = ${x + y}`
// "1 + 2 = 3"

`${x} + ${y * 2} = ${x + y * 2}`
// "1 + 4 = 5"

var obj = {x: 1, y: 2};
`${obj.x + obj.y}`
// 3

String templates also support nesting

const tmpl = addrs => `
  <table>
  ${addrs.map(addr => `
    <tr><td>${addr.first}</td></tr>
    <tr><td>${addr.last}</td></tr>
  `).join('')}
  </table>
`;
const data = [
    { first: '<Jane>', last: 'Bond' },
    { first: 'Lars', last: '<Croft>' },
];

console.log(tmpl(data));
// <table>
//
//   <tr><td><Jane></td></tr>
//   <tr><td>Bond</td></tr>
//
//   <tr><td>Lars</td></tr>
//   <tr><td><Croft></td></tr>
//
// </table>

Default value

In the past, when we declared a function with many parameters, we couldn't specify the default value directly, all of which would be handled by many default configurations.

function log(x, y) {
  y = y || 'World';
  console.log(x, y);
}

But this approach is not safe if we assign values like this.

log('Hello') // Hello World
log('Hello', 'China') // Hello China
log('Hello', '') // Hello World

ES6 allows default values for the parameters of a function, which are written directly after the parameter definition.

function log(x, y = 'World') {
  console.log(x, y);
}

log('Hello') // Hello World
log('Hello', 'China') // Hello China
log('Hello', '') // Hello

rest parameter

ES6 introduces the rest parameter (in the form of "... variable name") to obtain the redundant parameters of the function, so that the arguments object is not needed. The rest parameter collocation variable is an array, which puts the redundant parameters into the array.

function add(...values) {
  let sum = 0;

  for (var val of values) {
    sum += val;
  }

  return sum;
}

add(2, 5, 3) // 10

Extension operator...

It is like the inverse operation of rest parameters, which converts an array into a comma-separated sequence of parameters.

console.log(...[1, 2, 3])
// 1 2 3

console.log(1, ...[2, 3, 4], 5)
// 1 2 3 4 5

[...document.querySelectorAll('div')]
// [<div>, <div>, <div>]

Reference material

Posted by capslock118 on Mon, 08 Apr 2019 16:27:31 -0700