ECMAScript6 Quick Start Guide, starting with ecmascript6

Source: Internet
Author: User

ECMAScript6 Quick Start Guide, starting with ecmascript6

Introduction

ECMAScript 6 is the next JavaScript standard and is under rapid development. The goal of ECMAScript 6 is, is an automatic generator that enables JavaScript to write complex applications, function libraries, and code ). The latest browser already partially supports the syntax of ECMAScript 6. Currently, ECMAScript 6 is basically the industry standard, and its popularity is much faster than that of es5, the main reason is that modern browsers support ES6 quite quickly. Especially Chrome and Firefox have already supported the vast majority of ES6 features.

1. let, const, and block Scope

Let allows the creation of block-level scopes. ES6 recommends using let to define variables in functions, rather than var:

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

Another variable declaration method that is effective in block-level scope is const, which can declare a constant. In ES6, the const declared constant is similar to a pointer, which points to a reference, that is, this "constant" is not static, such:

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

Note the following points:

Variables declared by the let keyword do not have the hoisting feature

The let and const statements are valid only in the nearest block (within curly brackets ).

Use uppercase variables when using the constant const declaration, such as CAPITAL_CASING

Const must be assigned a value during declaration.

2. Arrow Functions)

In ES6, the arrow function is a short form of the function. Wrap the parameter with parentheses, followed by a =>, followed by the function body:

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

Note that the getPrice arrow function in the chestnut above uses a concise function body, which does not require a reture statement. The following describes the normal function body:

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

Of course, the arrow function not only simplifies the code, but also always points to the object. For details, see the following Chestnuts:

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

We often need to use a variable to save this, and then reference it in the growUp function:

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

The use of Arrow functions saves the trouble:

Function Person () {this. age = 0; setInterval () => {// | this | point to the person object this. age ++ ;}, 1000) ;}var person = new Person ();

3. Default Value of function parameters

In ES6, you can set the default value for function parameters:

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

4. Spread/Rest Operators

The Spread/Rest operator refers to.... Whether it is Spread or Rest depends on the context.

When used in the iterator, It is a Spread OPERATOR:

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

When used for parameter passing by functions, it is a Rest OPERATOR:

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

5. Object lexical Extension

ES6 allows you to declare that attribute variables and function definition methods can be initialized using the abbreviated syntax when the object literal volume is used, and computing operations can be performed on the object attributes:

Function getCar (make, model, value) {return {// short variable make, // equivalent to make: make model, // equivalent to model: model value, // equivalent to value: value // The attribute can be calculated using an expression ['make' + make]: true, // ignore the 'function' keyword abbreviated as the object function depreciate () {this. value-= 2500 ;};}let car = getCar ('barret ', 'lil', 40000); // output: {// make: 'barret ', // model: 'lil', // value: 40000, // makeBarret: true, // depreciate: function ()//}

6. Binary and octal literal

ES6 supports binary and octal literal values. You can add 0o or 0O before a number to convert it to binary values:

Let oValue = 0o10; console. log (oValue); // 8 let bValue = 0b10; // use '0b' or '0b' console for binary. log (bValue); // 2

7. Deconstruct of objects and Arrays

Deconstruct can avoid generating intermediate variables when assigning values to objects:

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

ES6 allows the super method in the object:

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. template syntax and Separator

ES6 has a very simple way to assemble a bunch of strings and variables.

$ {...} Is used to render a variable.
'As Separator

let user = 'Barret';console.log(`Hi ${user}!`); // Hi Barret!

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

For... of is used to traverse an iterator, such as an array:

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

For... in is used to traverse the attributes of an object:

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 contains two new data structure sets: Map and WeakMap. In fact, each object can be considered as a Map.

An object consists of multiple key-val pairs. In Map, any type can be used as the key of the object, for example:

Var myMap = new Map (); var keyString = "a string", keyObj = {}, keyFunc = function () {}; // set the value of myMap. set (keyString, "value associated with 'a string'"); myMap. set (keyObj, "value and keyObj Association"); myMap. set (keyFunc, "value and keyFunc Association"); myMap. size; // 3 // obtain the value myMap. get (keyString); // "value is associated with 'a string'" myMap. get (keyObj); // "value and keyObj are associated with" myMap. get (keyFunc); // "correlation between value and keyFunc"

WeakMap

WeakMap is a Map, but all its keys are weak references. This means that we do not consider garbage collection in WeakMap. We do not need to worry about memory leakage when using it.

Another note is that all keys of WeakMap must be objects. 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); // truew.delete(o1);w.has(o1); // false

12. Set and WeakSet

A Set object is a Set of non-repeated values. duplicate values are ignored. The value type can be of the original type or reference type:

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

You can use forEach and for... of to traverse the Set object:

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 has the delete () and clear () methods.

WeakSet

Similar to WeakMap, The WeakSet object allows you to save weak references of objects in a collection. Objects in WeakSet can only appear once:

Var ws = new WeakSet (); var obj ={}; var foo ={}; ws. add (window); ws. add (obj); ws. has (window); // truews. has (foo); // false. foo is not successfully added to ws. delete (window); // delete the window object ws from the combination. has (window); // false. The window object has been deleted.

13. Class

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

Use the static keyword in the function to define the methods and attributes of the constructor:

class Task { constructor() { console.log("task instantiated!"); }  showId() { console.log(23); }  static loadAll() { console.log("Loading all tasks.."); }} console.log(typeof Task); // functionlet task = new Task(); // "task instantiated!"task.showId(); // 23Task.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 to inherit the parent class. Note that the constructor function of the subclass needs to execute the super () function.

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

Read here

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.