Overview of new features of ES6 _javascript tips

Source: Internet
Author: User
Tags export class generator instance method new set object object pow

Nick Justice is a member of the GitHub developer program. Before the ES6 language standard was released, he used ES6 features in his projects with translators such as Babel and the latest version of browsers. He believes that the new features of ES6 will dramatically change the way JavaScript is written.

ES6 (ECMAScript 6) is the upcoming new version of the JavaScript language standard, code-named Harmony (meaning of harmony, obviously did not keep pace with our country, we have entered the Chinese Dream version). The last standard was enacted in 2009 ES5. The ES6 is currently in the process of standardization and is expected to release the officially finalized version in December 14. But most of the standards are in place, and browser support for ES6 is also being implemented.

Although the development of technology is too fast, but we continue to learn the pace, will not be eliminated by the new technology, the following we together to learn the new characteristics of ES6 it.

Arrow operator

If you can C # or Java, you definitely know the lambda expression, the new arrow operator in ES6 =>. It simplifies the writing of functions. The left side of the operator is the input parameter, while the right-hand side is the operation performed and the returned value inputs=>outputs.

We know that in JS callback is a regular thing, and the general callback in the form of anonymous functions, each time need to write a function, very cumbersome. The callback can be written easily when the arrow operator is introduced. Take a look at the following example:

var array = [1,2,3];
Traditional writing
Array.foreach (function (v) {
console.log (v);
});
ES6 Writing

Support for classes

ES6 added support for classes, introducing the Class keyword (in fact, the class is always reserved in JavaScript for the purpose of taking into account the possibility that it will be used in a later version of it, and is now finally useful). JS itself is object-oriented, the class provided in the ES6 is actually only the JS prototype packaging. With native class support now available, object creation, inheritance is more intuitive and concepts such as invocation of parent methods, instantiation, static methods, and constructors are more visualized.

The following code shows the use of classes in ES6:

Class
Animal {
//ES6 New builder
Constructor (name) {
this.name = name;
}
Instance method
Sayname () {
console.log (' My name is ' + this.name);
}
}
Class
programmer extends Animal {
constructor (name) {
//directly invokes the parent class constructor to initialize
super (name);
} Program
() {
console.log ("I ' m coding ...");
}
Test our class
var animal = new Animal (' dummy '),
wayou = new Programmer (' wayou ');
Animal.sayname (); Output ' My name is dummy '
wayou.sayname ()//Output ' My name is Wayou '

Enhanced object literal

The object literal is enhanced, the writing is more concise and flexible, and there are more things to do when defining objects. The specific performance in:

1. You can define a prototype in the literal volume of an object

2. Definition method can be used without function keyword

3. Direct call to the parent class method

As a result, object literals are more consistent with the class concepts mentioned earlier, and are easier to write object-oriented JavaScript.

Object literal is created by object
var human = { 
Breathe () {
console.log (' breathing ... ');
}
;
var worker = { 
__proto__: Human,//Set this object's prototype to human, equivalent to inheriting human company
: ' Freelancer ',
work () {
Console.log (' working ... ');
}
;
Human.breathe (); Output ' breathing ... '
//Call inherited Breathe method

String templates

The string template is relatively straightforward. ES6 allows the use of inverted quotes ' to create a string that can contain a variable ${vraible} enclosed by a dollar sign plus curly braces. If you've ever used a back-end strongly typed language like C #, you shouldn't be unfamiliar with this feature.

Generates a random number
var num = Math.random ();
Output this number to the console 
console.log (' Your num is ${num} ');

Deconstruction

automatically resolves the values in an array or object. For example, if a function returns more than one value, the general practice is to return an object and return each value as the property of the object. In ES6, however, by using the feature of deconstruction, you can return an array directly, and then the values in the array are automatically parsed into the corresponding variables that receive the value.

function Getval () {
return[1,2];
}
var [x,y] = Getval (),///function return value deconstruction
console.log (' x: ' + x + ', y: ' + y);/output: X:1, Y:2
[name,,age] = [' wayou ', ' Male ' , ' Secrect ']; Array Deconstruction

Parameter default value, indefinite parameter, expand parameter

Default parameter values

You can now specify the default value of the parameter when you define the function, instead of using the logic or the operator to achieve the goal as before.

function SayHello (name) {
//traditional way of specifying default parameters
var name = name | | ' Dude ';
Console.log (' Hello ' + name);
} 
SayHello (); Output: Hello dude
sayhello (' wayou ');/output: Hello wayou
//Use the ES6 default parameter
function SayHello2 (name = ' Dude ') { C18/>console.log (' Hello${name} ');
SayHello2 (); Output: Hello dude

Indefinite parameters

An indeterminate parameter is an unnamed parameter that receives an indefinite number of arguments in a function using named parameters. This is just a syntactic candy, and we can do that by arguments variables in the previous JavaScript code. Indefinite parameters are formatted with three periods followed by variable names that represent all indeterminate parameters.

For example, in the following example, ... x represents all parameters that are passed in to the Add function.

function
Add (... x) {return
x.reduce (m,n) => m+n) with
all parameters added;
Pass any number of parameters
Console.log (Add (1,2,3));//output: 6

Expand parameters

The extension argument is another form of syntactic sugar that allows you to pass an array or a class array directly as a function parameter without having to apply.

var people = [' wayou ', ' John ', ' Sherlock '];
The SayHello function would have received three separate parameters man one, human two and human three
function SayHello (people1, People2, people3) {
console.log (' hello${ People1}, ${people2}, ${people3} ');
But we pass an array in the form of an extension parameter, which maps well to each individual parameter
SayHello (... people);//output: Hello wayou,john,sherlock
//And in the past, If you need to pass an array as a parameter, we need to use the Apply method of the function

Let and const keywords

Let can be viewed as VAR, except that its defined variables are limited to a certain range to be used, and leaving this range is not valid. The const is intuitive and is used to define constants, that is, variables that cannot be changed.

for (let i=0; i<2; i++) {
console.log (i);//output: 0,1
}

For value traversal

We all know that for-in loops are used to traverse an array, an array of classes, or an object, the newly introduced for of the loop function in ES6 is similar, unlike each loop it provides a value instead of an ordinal.

var somearray = ["A", "B", "C"];
for (v Somearray) {
console.log (v);//Output A,b,c

Iterator, generator

1.iterator: It is an object that has a next method that returns an object {Done,value}, which contains two attributes, the done of a Boolean type, and the value containing any value

2.iterable: This is an object that has a obj[@ @iterator] method that returns a iterator

3.generator: It is a special kind of iterator. The inverse next method can receive a parameter and the return value depends on its constructor (generator function). Generator also has a throw method

4.generator function: That is, the generator constructor. You can use the yield keyword within this function. Where the yield appears, you can pass the value to the outside by the generator next or throw method. The generator function is declared by function*.

5.yield keyword: it can suspend the execution of functions, and then enter the function to continue execution

Module

In the ES6 standard, JavaScript native supports module. The concept of modularity in a small block that divides JS code into different functions is prevalent in a number of tripartite specifications, such as the COMMONJS and AMD models.

The different functions of the code are written in different files, the modules only need to export the common interface part, and then through the import of modules can be used elsewhere.

Point.js
Module "point" {
Export class Point {
Constructor (x,y) {public
x=x;
public y=y;
}
}
Myapp.js
//Declares the referenced module 
"/point.js";
As can be seen here, although the referenced module is declared, it is possible to import the import point from "point" by specifying the desired part
;
var origin = new Point (0,0);
Console.log (origin); 
Map,set and Weakmap,weakset

These are the newly added collection types, providing a more convenient way to get property values, without using hasOwnProperty as before to check whether a property belongs to the prototype chain or the current object. At the same time, there is a special Get,set method when the attribute value is added and obtained.

//Sets var s = new Set (), S.add ("Hello"). Add ("Goodbye"); s.size = = 2; S.has ("hello") = =
= true;
Maps var m = new Map ();
M.set ("Hello", 42);
M.set (S, 34); 
M.get (s) = = 34; Sometimes we use objects as keys for an object to hold attribute values, and common collection types, such as simple objects, prevent the garbage collector from reclaiming objects that exist as property keys, and are at risk of causing memory leaks.
While Weakmap,weakset is more secure, these objects that act as property keys are recycled if they are not referenced by other variables, specifically the following example://Weak Maps var wm = new Weakmap ();
Wm.set (S, {extra:42});
Wm.size = = undefined//object released//Weak Sets var ws = new Weakset (); Ws.add ({data:42}); Because this temporary object that is added to WS has no other variables to reference it, WS does not save its value, which means that this addition is not meant to be. Proxies proxy can listen to what's happening on the object and perform some action after these things happen.
All of a sudden, we have a strong ability to track an object, but also useful in data binding.
Defines the target object being listened to var engineer = {name: ' Joe sixpack ', salary:50}; Define handler var interceptor = {Set:function (receiver, property, value) {Console.log (property, ' are changed to ', value); rec
Eiver[property] = value;
}
};
Create a proxy to listen engineer = Proxy (engineer, Interceptor); Make some changes to trigger agent engineer.salary = 60; Console output: Salary is changed 

I have added the code above to explain it further. For handlers, after a corresponding event occurs on the object being listened to, the method inside the handler is invoked, and in the example above we set the handler function of the set, indicating that if the property of the object we are listening to is changed, that is set, the handler will be invoked. At the same time, it is possible to know which property is changed and what value to change by using parameters.

Symbols

We know that the object is actually a collection of key-value pairs, and the key is usually a string. And now, in addition to strings, we can use the value of symbol as the key to the object. Symbol is a basic type, like a number, a string, and a Boolean, which is not an object. Symbol is generated by calling the symbol function, which receives an optional name argument, which returns the symbol that is unique. You can then use this return value as the object's key. Symbol can also be used to create private properties that cannot be accessed directly from the property value as a key by symbol.

(function () {//create symbol var key = symbol (' key '); function MyClass (privatedata) {This[key] = Privatedata;}
Myclass.prototype = {dostuff:function () {...} This[key] ...}};
})();
var c = new MyClass ("Hello");
c["key"] = = = undefined//cannot access this property because it is a private Math,number,string,object new API that adds a lot of new APIs to math,number,string and Object. Number//The minimum difference between two numbers is Number.epsilon//To determine whether it is an integer number.isinteger (Infinity)//False//To determine whether it is a non-numeric Number.isnan ("Na  N ")//False//Math Math.acosh (3)//1.762747174039086 Math.hypot (3,4)//5 Math.imul (Math.pow (2,32)-1, Math.pow (2,32)-2) 2//String "ABCDE". Contains ("CD"/True "ABC". Repeat (3)//"ABCABCABC"//array//Convert a class array object or an iterative object to a real array Array.fro M (Document.queryselectorall (' * '))//Put multiple parameters of any type of it in an array and return Array.of (1,2,3)//To replace or fill a fixed value with the values of all elements of a specified interval in an array [ 0,0,0].fill (7,1)//[0,7,7]//is used to find the index of a specified element in the array, and if the specified element is not found, return 1 [1,2,3].findindex (x => x = = 2)/1//return an array It Erator object that contains the key value pairs for each index in the array ["A", "B", "C"].entries ()//iterator [0, "A "], [1," B "], [2," C "]//returns an iterator for an array index [" a "," B "," C "].keys ()//iterator 0, 1, 2//Returns a new array iterator object that contains the values for each index of the array [ "A", "B", "C"].values ()//iterator "a", "B", "C"//Object Object.assign (point, {origin:new point (0,0)}) promises Promise S is a pattern for handling asynchronous operations, which were previously implemented in many tripartite libraries, such as the deferred object of jquery.
When you initiate an asynchronous request and bind the. When (), the. Done () and other event handlers are actually applying the promise mode. Create promise var promise = new Promise (function (resolve,reject) {//Make some asynchronous or time-consuming operations if (///If successful/*) {Resolve ("Stuff worked!"
);
else {reject (Error ("It Broke");}); Binding handler Promise.then (function (Result) {//Promise the successful Word will execute here console.log (cause);//"Stuff worked!"}, function (err) {/ /Promise Failure will execute here console.log (err); Error: "It Broke"});

About the new features of ES6 to introduce so many people, I hope to help you!

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.