ES6 articles

ES6 new features you know how much?

Everest Training  May 17

ES6 new features

 

Characteristics ES6 more, it will be released in ES5 standardized after nearly six years (2009-11 to 2015-6). Large time span between the two versions released, so characteristic of ES6 more.

Here are a few commonly used:

 

  • class

  • Modular

  • Arrow function

  • Function parameter default values

  • Template string

  • Deconstruction assignment

  • Extended operator

  • Object Properties shorthand

  • Promise

  • Let the Const

 

1. class (class)

 

Familiar with Java, object-c, c #, etc. pure object-oriented language developers, will have a special feeling for the class. ES6 introduced a class (class), so the JavaScript object-oriented programming has become more simple and easy to understand.

 

 class Animal {
    // 构造函数,实例化的时候将会被调用,如果不指定,那么会有一个不带参数的默认构造函数.
    constructor(name,color) {
      this.name = name;
      this.color = color;
    }
    // toString 是原型对象上的属性
    toString() {
      console.log('name:' + this.name + ',color:' + this.color);

    }
  }

 var animal = new Animal('dog','white');//实例化Animal
 animal.toString();

 console.log(animal.hasOwnProperty('name')); //true
 console.log(animal.hasOwnProperty('toString')); // false
 console.log(animal.__proto__.hasOwnProperty('toString')); // true

 class Cat extends Animal {
  constructor(action) {
    // 子类必须要在constructor中指定super 函数,否则在新建实例的时候会报错.
    // 如果没有置顶consructor,默认带super函数的constructor将会被添加、
    super('cat','white');
    this.action = action;
  }
  toString() {
    console.log(super.toString());
  }
 }

 var cat = new Cat('catch')
 cat.toString();

 // 实例cat 是 Cat 和 Animal 的实例,和Es5完全一致。
 console.log(cat instanceof Cat); // true
 console.log(cat instanceof Animal); // true

 

2. Modular (Module)

 

ES5 not support modular native, ES6 been added in the module as an important part. Functional modules mainly by export and import components. Each module has its own call each other the relationship between the individual scope, the module is exposed to the external interface module specified by export, to refer to other modules provide the interface through import. It also created a space for the module name, to prevent naming conflicts function.

 

Export (export)

 

ES6 allows using the export module to derive a plurality of variable or function.

 

Export variables

 

//test.js
export var name = 'Rainbow'

 

ES6 not only support the export of variables, constants also supports exporting. export const sqrt = Math.sqrt; // export constants

 

ES6 a file as a module, the module above by a variable output export outwardly. Wangwaimian a module may be simultaneously output a plurality of variables.

 

//test.js
 var name = 'Rainbow';
 var age = '24';
 export {name, age};

 

Export function

 

// myModule.js
export function myModule(someArg) {
  return someArg;

 

Import (import)

Good definition output module can be later referenced by another module import.

import {myModule} from 'myModule';// main.js
import {name,age} from 'test';// test.js

 

An import statement to import the default functions and other variables at the same time. import defaultMethod, {otherMethod} from 'xxx.js';

 

3. arrow (Arrow) function

 

ES6 This is one of the most exciting features. => Keyword function is not just an abbreviation, it also brings other benefits. Arrow share the same this function and its code is surrounded, can help you a good solution to this problem is pointing. Experienced JavaScript developers are familiar with, such as var self = this; var that = this or that references the periphery of this mode. But with =>, there is no need of this model.

 

Structure function of the arrow

 

Arrow function => empty parentheses preceded by a single parameter name, or by a plurality of brackets parameter name, and then expression can be an arrow (as the return value of the function), or in braces since the body of the function (need to return to their own values ​​return, otherwise return is undefined).

 

// 箭头函数的例子
()=>1
v=>v+1
(a,b)=>a+b
()=>{
    alert("foo");
}
e=>{
    if (e == 0){
        return 0;
    }
    return 1000/e;
}

 

When unloading trap listener

Out:

 

class PauseMenu extends React.Component{
    componentWillMount(){
        AppStateIOS.addEventListener('change', this.onAppPaused.bind(this));
    }
    componentWillUnmount(){
        AppStateIOS.removeEventListener('change', this.onAppPaused.bind(this));
    }
    onAppPaused(event){
    }
}

 

The right way:

 

class PauseMenu extends React.Component{
    constructor(props){
        super(props);
        this._onAppPaused = this.onAppPaused.bind(this);
    }
    componentWillMount(){
        AppStateIOS.addEventListener('change', this._onAppPaused);
    }
    componentWillUnmount(){
        AppStateIOS.removeEventListener('change', this._onAppPaused);
    }
    onAppPaused(event){
    }
}

 

In addition to these practices, we can also do this:

 

class PauseMenu extends React.Component{
    componentWillMount(){
        AppStateIOS.addEventListener('change', this.onAppPaused);
    }
    componentWillUnmount(){
        AppStateIOS.removeEventListener('change', this.onAppPaused);
    }
    onAppPaused = (event) => {
        //把函数直接作为一个arrow function的属性来定义,初始化的时候就绑定好了this指针
    }
}

 

Note that: either bind or arrow function is executed each time the return is a new function reference, so if you need a reference function to do something else (such as unloading listener), then you must save yourself this reference.

 

4. Function Default parameters

 

ES6 support in the definition of the function of time to set default values:

 

function foo(height = 50, color = 'red')
{
    // ...
}

 

Do not use the default values:

 

function foo(height, color)
{
    var height = height || 50;
    var color = color || 'red';
    //...
}

 

Write generally no problem, but when a Boolean value of false parameters, they will have a problem. For example, we call this function foo:

 

foo(0, "")

 

Since the Boolean value false 0, so that the value will be 50 height. Similarly the color value of 'red'.

 

So, the function parameter default values ​​not only is the code more concise and can avoid some of the problems.

 

The template string

 

ES6 support template string, string concatenation makes more simple and intuitive.

Do not use a template string:

 

var name = 'Your name is ' + first + ' ' + last + '.'

 

Use template string:

 

var name = `Your name is ${first} ${last}.`

 

 

In ES6} by $ {string concatenation can be done, simply being variable in braces.

 

6. deconstruction assignment

 

Deconstruction assignment syntax is an expression of JavaScript, you can easily assign values ​​to variables defined rapid extraction from the array or object.

 

Gets the value of the array

And acquiring from the array values ​​assigned to variables, array variables corresponding to the order of the objects in the order.

 

var foo = ["one", "two", "three", "four"];

var [one, two, three] = foo;
console.log(one); // "one"
console.log(two); // "two"
console.log(three); // "three"

//如果你要忽略某些值,你可以按照下面的写法获取你想要的值
var [first, , , last] = foo;
console.log(first); // "one"
console.log(last); // "four"

//你也可以这样写
var a, b; //先声明变量

[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2

 

If you do not get the value from the array, you can set a default value for the variable.

 

var a, b;

[a=5, b=7] = [1];
console.log(a); // 1
console.log(b); // 7

 

You can easily exchange the values ​​of two variables by destructuring assignment.

 

var a = 1;
var b = 3;

[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1

 

Gets the value of the object

const student = {
  name:'Ming',
  age:'18',
  city:'Shanghai'  
};

const {name,age,city} = student;
console.log(name); // "Ming"
console.log(age); // "18"
console.log(city); // "Shanghai"

 

7. extended operator (Spread operator)

 

... operator can extend the syntax of the string array expression level or function call deployed / array configuration; may also be configured at the object, the object will be expanded by the expression of key-value method.

 

grammar

Function call

 

myFunction(...iterableObj);

 

String or array configuration:

 

[...iterableObj, '4', ...'hello', 6];

 

When the object is constructed, cloning or attribute copy (ECMAScript 2018 Added features specification):

 

let objClone = { ...obj };

Scenarios

Extended operator using the function call

 

function sum(x, y, z) {
  return x + y + z;
}
const numbers = [1, 2, 3];

//不使用延展操作符
console.log(sum.apply(null, numbers));

//使用延展操作符
console.log(sum(...numbers));// 6

 

Building Arrays

 

The syntax is not expanded when used in combination can only push, splice, concat and other methods to the array elements have become part of the new array. With the expanded syntax constructs a new array will become more simple, more elegant:

 

const stuendts = ['Jine','Tom']; 
const persons = ['Tony',... stuendts,'Aaron','Anna'];
conslog.log(persions)// ["Tony", "Jine", "Tom", "Aaron", "Anna"]

 

Expand the parameter list and the like,  ... when constructing the array of words, can be used many times in any position.

 

Array copy

 

var arr = [1, 2, 3];
var arr2 = [...arr]; // 等同于 arr.slice()
arr2.push(4); 
console.log(arr2)//[1, 2, 3, 4]

 

Expand the syntax and Object.assign () consistent behavior, execution is shallow copy (only traverse one).

 

Connecting a plurality of arrays

 

var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
var arr3 = [...arr1, ...arr2];// 将 arr2 中所有元素附加到 arr1 后面并返回
//等同于
var arr4 = arr1.concat(arr2);

In the spreading operator ECMAScript 2018 adds support for objects

var obj1 = { foo: 'bar', x: 42 };
var obj2 = { foo: 'baz', y: 13 };

var clonedObj = { ...obj1 };
// 克隆后的对象: { foo: "bar", x: 42 }

var mergedObj = { ...obj1, ...obj2 };
// 合并后的对象: { foo: "baz", x: 42, y: 13 }

 

The application React

 

We usually one component in the package, will open to the public some of the props used to implement functions. Use transfer props should be displayed outside most cases. But when a large amount of transfer The props, very cumbersome, then we can use ... (extended operator, for all attributes taken to traverse the object parameters) to pass.

 

Under normal circumstances we should write

 

<CustomComponent name ='Jine' age ={21} />

 

Use ..., equivalent to the above wording

 

const params = {
    name: 'Jine',
    age: 21
}
<CustomComponent {...params} />

 

With destructuring assignment to avoid unwanted incoming parameters

 

var params = {
    name: '123',
    title: '456',
    type: 'aaa'
}

var { type, ...other } = params;

<CustomComponent type='normal' number={2} {...other} />
//等同于
<CustomComponent type='normal' number={2} name='123' title='456' />

 

 

8. Object Properties shorthand

 

It allows us to set the properties of an object in the ES6 when not specify the property name.

 

Do not use ES6

 

const name='Ming',age='18',city='Shanghai';

const student = {
    name:name,
    age:age,
    city:city
};
console.log(student);//{name: "Ming", age: "18", city: "Shanghai"}

 

Object must contain attributes and values, it is very redundant.

 

Use ES6

 

const name='Ming',age='18',city='Shanghai';

const student = {
    name,
    age,
    city
};
console.log(student);//{name: "Ming", age: "18", city: "Shanghai"}

 

Objects directly write variables, it is very simple.

 

9.Promise

Promise asynchronous programming is a solution more elegant than traditional solutions callback. It was first proposed and implemented by the community, ES6 be written into the standard language, unified usage, native in the Promise object.

 

Do not use ES6

Nested two setTimeout callback functions:

 

setTimeout(function()
{
    console.log('Hello'); // 1秒后输出"Hello"
    setTimeout(function()
    {
        console.log('Hi'); // 2秒后输出"Hi"
    }, 1000);
}, 1000);

 

Use ES6

 

var waitSecond = new Promise(function(resolve, reject)
{
    setTimeout(resolve, 1000);
});

waitSecond
    .then(function()
    {
      console.log("Hello"); // 1秒后输出"Hello"
      return waitSecond;
    })
    .then(function()
    {
        console.log("Hi"); // 2秒后输出"Hi"
    });

 

The above code uses two serial asynchronous programming then carried out, and to prevent callback hell:

10. Support and let const

Before JS is not block-level scope, const and let it convenient to fill the gaps, const and let all block-level scope.

Var variables defined as a function of level scope:

 

{
  var a = 10;
}

console.log(a); // 输出10

 

Const let the variables defined for the block-level scope: 

{
  let a = 10;
}

console.log(a); //-1 or Error“ReferenceError: a is not defined”

 

Guess you like

Origin www.cnblogs.com/still1/p/11008087.html