ECMAScript 6 (ES6) Concise Guide

ECMAScript 6 Concise Guide

ECMAScript 6 now basically become an industry standard, its popularity a lot faster than ES5, mainly due to modern browsers support ES6 fairly quickly, especially in Chrome and Firefox browsers, most of those features have been ES6 support.


 
    

Original: https: //github.com/metagrover/ES6-for-humans

Translation: http: //www.barretlee.com/blog/2016/07/09/a-kickstarter-guide-to-writing-es6/

1. let, const and block scopes

let allows the creation of block-level scope, for ES6 recommended let variables defined in the function, rather than var:

var a = 2;
{
  let a = 3;
  console.log(a); // 3
}
console.log(a); // 2

 

Also in the block-level scope effective manner is another variable declared const, it can declare a constant. ES6, the constants const declaration is similar to a pointer, it points to a quote, that this "constant" is not static, such as:

{
  const ARR = [5,6];
  ARR.push(7);
  console.log(ARR); // [5,6,7]
  ARR = 10; // TypeError
}

 

There are several points to note:

  • Variables let keyword does not have the variable declaration lift (hoisting) properties
  • const statement and let in only one of the closest block (braces) effective
  • When using a constant const statement, use an uppercase variables, such as: CAPITAL_CASING
  • const must be assigned at the time of declaration

2. Functions of the arrow (Arrow Functions)

ES6, the arrow function is a shorthand form of a function, parameter parentheses package, followed by a =>, followed by the body of the function:

var getPrice = function() {
  return 4.55;
};
 
// Implementation with Arrow Function
var getPrice = () => 4.55;

 

Note that, in the above example uses a simple function getPrice arrows body of the function, it does not return statement, the following example uses the normal function of the body:

let arr = ['apple', 'banana', 'orange'];
 
let breakfast = arr.map(fruit => {
  return fruit + 's';
});
 
console.log(breakfast); // apples bananas oranges

 

Of course, not just a function of the arrow so that code becomes simple, this function is always binding always points to the object itself. Specific can look at the following examples:

function the Person () {
   the this .age = 0 ; 
 
  the setInterval ( function growUp () {
     // in a non-strict mode, growUp () this function points to the window object 
    the this .age ++ ; 
  }, 1000 ); 
} 
var Person = new new the Person ();

 

We often need to use a variable to hold this, then referenced in growUp function:

function Person() {
  var self = this;
  self.age = 0;
 
  setInterval(function growUp() {
    self.age++;
  }, 1000);
}

 

Use the arrow function and can save the trouble:

function Person(){
  this.age = 0;
 
  setInterval(() => {
    // |this| 指向 person 对象
    this.age++;
  }, 1000);
}
 
var person = new Person();

 

3. Default function parameters

ES6 allowed you to set default values ​​for function parameters:

let getFinalPrice = (price, tax=0.7) => price + price * tax;
getFinalPrice(500); // 850

 

4. Spread / Rest operator

Spread / Rest ... operator refers, in particular Spread Rest need to see or Context.

When the iterator is used, it is an operator Spread:

function foo(x,y,z) {
  console.log(x,y,z);
}
 
let arr = [1,2,3];
foo(...arr); // 1 2 3

 

When the function is used when the transmission parameter is a Rest operator:

function foo(...args) {
  console.log(args);
}
foo( 1, 2, 3, 4, 5); // [1, 2, 3, 4, 5]

 

The extended objects lexical

ES6 allows the declaration syntax when using shorthand object literal, to initialize variables define properties and methods function, and allows calculation operations in the object properties:

function getCar (the make, Model, value) {
   return {
     // abbreviated variables 
    the make,   // equivalent to the make: the make 
    Model, // equivalent Model: Model 
    value, // equivalent value: value 
 
    // property can use an expression calcd 
    [ 'the make' the make +]: to true , 
 
    // ignore abbreviated `function` Image Object functions 
    depreciate () {
       the this .Value - = 2500 ; 
    } 
  }; 
} 
 
the let CAR = getCar ( 'Barret', 'Lee' , 40000 ); 
 
// Output: { 
//      the make: 'Barret', 
//     model:'Lee',
//     value: 40000,
//     makeKia: true,
//     depreciate: function()
// }

 

6. binary and octal literals

ES6 supports binary and octal literal, in front of a number by adding 0o or 0O to convert it to octal values:

= oValue the let 0o10; 
the console.log (oValue); // . 8 
 
the let bValue = 0b10; // binary `0b` use 0B` or` 
the console.log (bValue); // 2

 

7. objects and arrays deconstruction

Deconstruction can be avoided when the object is to produce an intermediate variable assignment:

function foo() {
  return [1,2,3];
}
let arr = foo(); // [1,2,3]
 
let [a, b, c] = foo();
console.log(a, b, c); // 1 2 3
 
function bar() {
  return {
    x: 4,
    y: 5,
    z: 6
  };
}
let {x: x, y: y, z: z} = bar();
console.log(x, y, z); // 4 5 6

 

8. Object superclass

The method allows the use of super ES6 in a subject:

var parent = {
  foo() {
    console.log("Hello from the Parent");
  }
}
 
var child = {
  foo() {
    super.foo();
    console.log("Hello from the Child");
  }
}
 
Object.setPrototypeOf(child, parent);
child.foo(); // Hello from the Parent
             // Hello from the Child

 

9. The template grammar and delimiter

ES6 there is a very simple method for assembling a bunch of strings and variables.

  • $ {...} for rendering variable a
  • `As a delimiter
let user = 'Barret';
console.log(`Hi ${user}!`); // Hi Barret!

 

10. for...of VS for...in

for ... of iterators for traversing a, such as an array:

let nicknames = ['di', 'boo', 'punkeye'];
nicknames.size = 3;
for (let nickname of nicknames) {
  console.log(nickname);
}
// 结果: di, boo, punkeye

 

for ... in to iterate object attributes:

let nicknames = ['di', 'boo', 'punkeye'];
nicknames.size = 3;
for (let nickname in nicknames) {
  console.log(nickname);
}
Result: 0, 1, 2, size

 

11. Map and WeakMap

ES6 in two new set of data structures: Map and WeakMap. Virtually every object can be seen as a Map.

An object composed of a plurality of key-val, in the Map, any type can be used as an object key, such as:

var the myMap = new new the Map (); 
 
var keyString = "A String" , 
    keyObj = {}, 
    keyfunc = function () {}; 
 
// set value 
myMap.set (keyString, "value of 'a string' association" ); 
myMap.set (keyObj, "associated with the value keyObj" ); 
myMap.set (keyfunc, "value associated with keyfunc" ); 
 
myMap.size; // . 3 
 
// Get value 
myMap.get (keyString);     // "value and 'a string' association " 
myMap.get (keyObj);        // " keyObj value associated with " 
the myMap.      get(keyFunc);      // "value associated with keyfunc"

 

WeakMap

WeakMap is a Map, but it's all the key are weak references, which means that when things do not consider garbage collection WeakMap, use it without worrying about memory leaks.

Another point to note is that all key WeakMap must be the object. It has only four methods delete (key), has (key), get (key) and set (key, val):

let w = new WeakMap();
w.set('a', 'b'); 
// Uncaught TypeError: Invalid value used as weak map key
 
var o1 = {},
    o2 = function(){},
    o3 = window;
 
w.set(o1, 37);
w.set(o2, "azerty");
w.set(o3, undefined);
 
w.get(o3); // undefined, because that is the set value
 
w.has(o1); // true
w.delete(o1);
w.has(o1); // false

 

12. Set and WeakSet

Set the object is a set of unique values, duplicate values ​​will be ignored, value types can be primitive types and reference types:

let mySet = new Set([1, 1, 2, 2, 3, 3]);
mySet.size; // 3
mySet.has(1); // true
mySet.add('strings');
mySet.add({ a: 1, b:2 });

 

By forEach and for ... of the object to traverse Set:

mySet.forEach((item) => {
  console.log(item);
    // 1
    // 2
    // 3
    // 'strings'
    // Object { a: 1, b: 2 }
});
 
for (let value of mySet) {
  console.log(value);
    // 1
    // 2
    // 3
    // 'strings'
    // Object { a: 1, b: 2 }
}

 

Set also have delete () and clear () method.

WeakSet

Similar WeakMap, WeakSet objects let you save a weak reference objects in a collection, objects in WeakSet allows only appear once:

var WS = new new WeakSet ();
 var obj = {};
 var foo = {}; 
 
ws.add (window); 
ws.add (obj); 
 
ws.has (window); // to true 
ws.has (foo) ;     // false, foo is not added successfully 
 
WS. the delete (window); // delete the object from the window Integrative 
ws.has (window);     // false, the window object that has been deleted

 

13. Class

ES6 have class syntax. It is worth noting that not a new object class inheritance model here, it's just syntactic sugar manifestation of the prototype chain.

Keywords used in the function definitions static constructor methods and properties:

class Task {
  constructor() {
    console.log("task instantiated!");
  }
 
  showId() {
    console.log(23);
  }
 
  static loadAll() {
    console.log("Loading all tasks..");
  }
}
 
console.log(typeof Task); // function
let task = new Task(); // "task instantiated!"
task.showId(); // 23
Task.loadAll(); // "Loading all tasks.."

 

Class inheritance and superset:

class Car {
  constructor() {
    console.log("Creating a new car");
  }
}
 
class Porsche extends Car {
  constructor() {
    super();
    console.log("Creating Porsche");
  }
}
 
let c = new Porsche();
// Creating a new car
// Creating Porsche

 

extends allows a subclass inherits the parent class, to be noted that, in the constructor of the subclass needs to perform super () function.

Of course, you can also call the parent class method in a subclass method, as super.parentMethodName ().

Read more here about the type of presentation.

There are a few points worth noting:

  • The class declaration will not lift (hoisting), if you want to use a Class, you must define it before use, otherwise it will throw an error ReferenceError
  • Function without using functions defined in the class keywords

14. Symbol

Symbol is a new data type, its value is unique, immutable. The purpose ES6 proposed symbol is to generate a unique identifier, but you can not access this identifier:

var sym = Symbol( "some optional description" );
console.log(typeof sym); // symbol

 

Note that, here, the front Symbol not use the new operator.

If it is used as an attribute of an object, then this property is not enumerable:

var o = {
    val: 10,
    [ Symbol("random") ]: "I'm a symbol",
};
 
console.log(Object.getOwnPropertyNames(o)); // val

 

To obtain the object symbol properties required Object.getOwnPropertySymbols (o).

15. iterator (Iterators)

Iterator allows access to each element of a data set of pointers to data collection when the last element that the iterator will quit. It provides the next () function to traverse a sequence, which returns a value attribute comprising the object and done.

ES6 can set the default traverse through Symbol.iterator to object whenever the object needs to be traversed, the implementation of its @@ iterator method can be used to obtain a return iterator value.

The default array is an iterator:

var arr = [11,12,13];
var itr = arr[Symbol.iterator]();
 
itr.next(); // { value: 11, done: false }
itr.next(); // { value: 12, done: false }
itr.next(); // { value: 13, done: false }
 
itr.next(); // { value: undefined, done: true }

 

You can [Symbol.iterator] () iterator from the definition of an object.

16. Generators

Generator function is a new feature for ES6, which allows objects may traverse a plurality of function return value is generated.

In use, you will see * syntax and a new keyword yield:

function *infiniteNumbers() {
  var n = 1;
  while (true){
    yield n++;
  }
}
 
var numbers = infiniteNumbers(); // returns an iterable object
 
numbers.next(); // { value: 1, done: false }
numbers.next(); // { value: 2, done: false }
numbers.next(); // { value: 3, done: false }

 

Each time yield executed, the return value becomes the next value of the iterator.

17. Promises

ES6 for Promise With native support, a Promise is a wait for the object to be executed asynchronously, when it is executed, its status becomes resolved or rejected.

var p = new Promise(function(resolve, reject) {  
  if (/* condition */) {
    // fulfilled successfully
    resolve(/* value */);  
  } else {
    // error, rejected
    reject(/* reason */);  
  }
});

 

Each has a .then Promise method, this method takes two parameters, a first callback handler is resolved state, a callback handler is rejected state:

p.then((val) => console.log("Promise Resolved", val),
       (err) => console.log("Promise Rejected", err));

 

Original: https: //github.com/metagrover/ES6-for-humans

Guess you like

Origin www.cnblogs.com/orangehero/p/11091462.html