ES6 new features Overview

Source: Internet
Author: User
Tags export class

http://es6.ruanyifeng.com/#README

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference

(1) Arrow operator

If you have C # or Java, you must 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, and the right side is the action to be taken and the value returned inputs=>outputs.
We know that the callback in JS is often the case, and the general callback in the form of anonymous functions, each time need to write a function, is very cumbersome. When the arrow operator is introduced, the callback can be easily written. Take a look at the following example:

var array = [n/a]; // Traditional notation Array.foreach (function(v) {    console.log (v);}); // ES6 notation array.foreach (v = console.log (v));

(2) Support for classes

ES6 added support for classes, introduced the class keyword (in fact, the class in JavaScript has always been reserved word, the purpose is to consider possible in the new version will be used, and now finally come in handy). JS itself is object-oriented, and the class provided in ES6 is actually just a wrapper for JS prototype mode. Now that the native class support is provided, object creation, inheritance is more intuitive, and concepts such as invocation, instantiation, static methods, and constructors of the parent method are more visualized.

The following code shows the use of the class in ES6:

//definition of Classclass Animal {//A new type of constructor in ES6Constructor (name) { This. Name =name; }    //instance MethodSayname () {Console.log (' My name is ' + This. Name); }}//Inheritance of Classesclass Programmer extends Animal {constructor (name) {//calling the parent class constructor directly for initializationsuper (name); } program () {Console.log ("I ' m coding ..."); }}//Test Our classvarAnimal =NewAnimal (' Dog '),
Wayou=NewProgrammer (' Cat '); Animal.sayname (); //Output ' My name is dog 'Wayou.sayname ();//Output ' My name is Cat 'Wayou.program ();//output ' I ' m coding ... '

(3) Enhanced object literals

Object literals are enhanced, the wording is more concise and flexible, and there are more things to do when defining objects. Specific performance in:

    1. You can define prototypes in object literals
    2. Definition methods can be used without the function keyword
    3. Calling the parent class method directly

In this way, object literals are more consistent with the class concepts mentioned earlier, and are easier to write when writing object-oriented JavaScript.

// creating objects from Object literals var human = {     Breathe () {        console.log (' breathing ... ');}    }; var worker = {     //  Set the prototype for this object to human, which is equivalent to inheriting humancompany    : ' Freelancer ' , Work    () {        console.log (' working ... ');     // output ' breathing ... ' // Call the inherited Breathe method // output ' breathing ... '

(4) String template

String templates are relatively straightforward to understand. ES6 is allowed to use anti-quotes ' to create a string that can contain a variable that is enclosed by a dollar sign and curly braces ${vraible} . If you have used a back-end strongly typed language such as C #, you should not be unfamiliar with this feature.

// generate a random number var num = math.random (); //  console.log (' Your num is ${num} ');

(5) Deconstruction

automatically resolves values in an array or object. For example, if a function returns multiple values, it is common practice to return an object that returns each value as a property of the object. In ES6, however, by using the Deconstruction feature, you can return an array directly, and the values in the array are automatically parsed into the corresponding variable that receives the value.

function Getval () {    return[];} var // Deconstruction of function return value // output: x:1, Y:2  //  array Deconstruction //

(6) Parameter default value, indefinite parameter, expand parameter

Default parameter values

It is now possible to specify the default value of a parameter when defining a function, rather than using logic or operators to achieve the purpose as before.

functionSayHello (name) {//traditional ways to specify default parameters    varName = Name | | ' Dude '; Console.log (' Hello ' +name);} SayHello (); //output: Hello dudeSayHello (' wayou ');//output: Hello wayou//using the default parameters of ES6functionSayHello2 (name = ' Dude '){console.log (' hello${name} ');} SayHello2 (); //output: Hello dudeSayHello2 (' wayou ');//output: Hello wayou
Expansion parameters

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

var people = [' wayou ', ' John ', ' Sherlock ']; // the SayHello function originally received three individual parameters man one, man two and man three function SayHello (People1, People2, people3) {    console.log (' Hello${people1}, ${people2}, ${people3} ');} // but we pass an array as an extension parameter, which maps nicely to each individual parameter // output: Hello wayou,john,sherlock // and in the past, if you need to pass an array as a parameter, we need to use the function's Apply method sayhello.apply (null//

(7) Let and const keywords

You can think of let as Var, except that the variable it defines is scoped to a specific range to be used, and leaving the range is invalid. Const is intuitive to define constants, which are variables that cannot be changed.

 for (Let i=0; i<2; i++) {    //  output: 0,1//  output: Undefined, error in strict mode

(8) for value traversal

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

var somearray = ["A", "B", "C"];  for (V of Somearray) {    //  output A,b,c}

(9) Iterator, generator

// iterator: It is an object that has a next method that returns an object {Done,value}, which contains two properties, a Boolean type of done and a value containing any values // iterable: This is an object that has a obj[@ @iterator] method, which returns a iterator // 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 //generator function: The generator constructor. The yield keyword can be used within this function. Where yield occurs, the value can be passed to the outside world via the next or throw method of the generator. The generator function is declared by the function* //yield keyword: it can pause the execution of a function, and can then go into the function to continue execution

(10) Module

In the ES6 standard, JavaScript native support module. This modular concept of splitting JS code into different functions is popular in a number of tripartite specifications, such as COMMONJS and AMD models.

The different functions of the code are written in separate files, each module only need to export the common interface section, and then through the module's import can be used elsewhere.

// point.jsmodule ' point ' {    Export class Point {        constructor (x, y) {public            x=x;            Public y=y;     }}} // Myapp.js //  module point from "/point.js"; // It can be seen here that, although the referenced module is declared, it can be imported by specifying the required parts for import point from the "point"; var New Point (0,0); Console.log (origin);

(11) Map,set and Weakmap,weakset

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

   var new Set (); S.add ("Hello"). Add ("goodbye" = = = 2; S.has (    true; // Maps var New Map (); M.set ("Hello",= = 34;

Sometimes we use objects as keys to hold property values, and ordinary collection types, such as simple objects, prevent the garbage collector from recycling objects that exist as property keys, and there is a risk of memory leaks. And the Weakmap,weakset is more secure, these objects as property keys if there are no other variables referencing them, it will be released by the collection, in particular, see the following example:

// Weak Maps var New        //object released//Weak sets var new   //  because this temporary object added to WS does not have other variables referencing it, WS does not save its value, which means that this addition does not actually mean

(12) Proxies

Proxy can listen to what is happening on the object and perform some corresponding actions after these things happen. All of a sudden, we have a strong ability to track an object, but also useful in data binding.

//define the target object being listened tovarEngineer = {name: ' Joe sixpack ', salary:50};//Defining HandlersvarInterceptor = {set:function(receiver, property, value) {Console.log,' is changed to ', value); Receiver[property]=value; }};//creating an agent for listeningEngineer =Proxy (engineer, Interceptor);//make some changes to trigger the proxyEngineer.salary = 60;//Console output: Salary is changed to

(13) Symbols

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

(function() {    //Create Symbol    varKey = Symbol ("Key"); functionMyClass (privatedata) { This[Key] =Privatedata; } Myclass.prototype={dostuff:function() {            ... This[key] ...} };}) ();varc =NewMyClass ("Hello"); c["key"] = = = undefined//The property cannot be accessed because it is private

(14) Math,number,string,object's new API

A number of new APIs have been added to math,number,string and object.

// Number//The smallest difference between the different two numberNumber.epsilon//determine if it is an integerNumber.isinteger (Infinity)//false//determines whether a non-numericNumber.isnan ("NaN")//false//MathMath.acosh (3)//1.762747174039086Math.hypot (3,4)//5Math.imul (Math.pow (2,32)-1, Math.pow (2,32)-2)//2//String"ABCDE". Contains ("CD")//true"ABC". Repeat (3)//"ABCABCABC"//Array//converts a class array object or an iterative object into a real arrayArray.from (Document.queryselectorall (' * ')))//put multiple arguments of any type of it in an array and returnArray.of (A)//converts the values of all elements of a specified interval in an array into a fixed value[0,0,0].fill (7,1)//[0,7,7]//used to find the index of a specified element in the array, or 1 if the specified element is not found[1,2,3].findindex (x = x = = 2)//1//returns an array Iterator object that contains the key-value pairs for each index in the array["A", "B", "C"].entries ()//iterator [0, "a"], [1, "B"], [2, "C"]//an iterator that returns 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"//ObjectObject.assign (point, {origin:NewPoint (0,0)})

(15) Promises

Promises is a pattern for handling asynchronous operations, previously implemented in many third-party libraries, such as jquery's deferred objects. When you initiate an asynchronous request and bind the. when (),. Do () event handlers, you are actually applying promise mode.

//Create PromisevarPromise =NewPromise (function(resolve,reject) {//perform some asynchronous or time-consuming operations    if(/*If successful*/) {Resolve ("Stuff worked!"); } Else{Reject (Error ("It broke")); }});//Binding HandlersPromise.then (function(Result) {//promise success will be executed here.Console.log (result);//"Stuff worked!"},function(err) {//promise failure will execute hereConsole.log (ERR);//Error: "It broke"

ES6 new features Overview

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.