New features of ES6-make the difference between front and back smaller

Source: Internet
Author: User
Tags export class

ES6 (ECMAScript 6) is the upcoming new version of the JavaScript language standard, codenamed Harmony (harmonious meaning, obviously did not keep pace with our country, we have entered the Chinese Dream version). The last standard was enacted in 2009 ES5. The current standardization of ES6 is underway and is expected to be released in December 14 in an officially finalized version. But most of the standards are already in place, and the browser support for ES6 is also being implemented.

Although the trend is too fast, but we continue to learn the pace, will not be left behind, the following to appreciate the next ES6 in the new features, a generation of JS style.

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 example below.
var array = [1, 2, 3];
//传统写法
array.forEach(function(v, i, a) {
console.log(v);
});
//ES6
array.forEach(v = > console.log(v));

2, the support of the class

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 classes in ES6

//Definition of class class Animal {    A new type of constructor in//es6Constructor (name) { This. name = name; }//Instance methodSayname () {Console.log (' My name is '+ This. name); }}//Inheritance of Class class Programmer extends Animal {Constructor (name) {//Direct call to parent class constructor for initialization        Super(name); } program () {Console.log ("I ' m coding ..."); }}//Test our classvarAnimal=NewAnimal (' Dummy '), wayou=NewProgrammer (' wayou '); Animal.sayname ();//Output ' My name is dummy 'Wayou.sayname ();//Output ' My name is Wayou '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:

    • You can define prototypes in object literals
    • Definition methods can be used without the function keyword
    • 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.

//Create object  var  human =  {Breathe () {Console log     (); }}; var  worker =  {__proto__: Human, //sets the prototype for this object to human, which is equivalent to inheriting human  company:  ' freelancer ' , work () { Console log     (); }};human Breathe (); //output ' breathing ... '  //calls the inherited Breathe method  Worker Breathe (); //output ' breathing ... '   
4. String template

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

//产生一个随机数var num=Math.random();//将这个数字输出到consoleconsole.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.

var [x,y]=getVal(),//函数返回值的解构    [name,,age]=[‘wayou‘,‘male‘,‘secrect‘];//数组解构function getVal() {    return12 ];}console.log(‘x:‘+x+‘, y:‘+y);//输出:x:1, y:2 console.log(‘name:‘+name+‘, age:‘+age);//输出: name:wayou, age:secrect 
6. 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++)console.log(i);//输出: 0,1console.log(i);//输出:undefined,严格模式下会报错
7. 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"a""b""c" ];forof someArray) {    console.log(v);//输出 a,b,c}
8. 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.js"point" {    export class Point {        constructor (x, y) {            public x = x;            public y = y;        }    }}// myapp.js//声明引用的模块from"/point.js";//这里可以看出,尽管声明了引用的模块,还是可以通过指定需要的部分进行导入from"point";varnew Point(00);console.log(origin);
9, 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 property value addition and acquisition.

//setsvarS= New Set(); s.Add"Hello").Add"Goodbye").Add"Hello"); s.Size=== 2; s.Has ("Hello")=== true;//MapsvarM= New Map(); m.Set("Hello", the); m.Set(S, the); m.Get (s)==  the;

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 reclaimed and released, specifically, see the following example

// Weak Mapsvarnew WeakMap();wm.set42undefined// Weak Setsvarnew42 });//因为添加到ws的这个临时对象没有其他变量引用它,所以ws不会保存它的值,也就是说这次添加其实没有意思
10, 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() {  // 创建symbol  var key = Symbol("key");  function MyClass(privateData) {    this[key] = privateData;  }  MyClass.prototype = {    function() {      ......    }  };})();var c = new MyClass("hello")c["key"] === undefined//无法访问该属性,因为是私有的
11, Math,number,string,object's new API

A number of new APIs have been added to math,number,string and object. The following code is also from Es6features, which provides a simple demonstration of these new APIs.

 Number. EPSILON Number. Isinteger (Infinity)//False Number. IsNaN ("NaN")//FalseMath. Acosh (3)//1.762747174039086Math. Hypot (3,4)//5Math. Imul (Math. POW (2, +) -1,Math. POW (2, +) -2)//2"ABCDE". Contains ("CD")//True"ABC". Repeat (3)//"ABCABCABC"Array. from (Document.queryselectorall (' * '))//Returns a real ArrayArray. of (1,2,3)//Similar to New Array (...), but without special one-arg behavior[0,0,0].fill (7,1)//[0,7,7][1,2,3].findindex (x = x = =2)//1["a","B","C"].entries ()//iterator [0, "a"], [1, "B"], [2, "C"]["a","B","C"].keys ()//Iterator 0, 1, 2["a","B","C"].values ()//iterator "a", "B", "C"Object. Assign (point, {origin:NewPoint (0,0) })
12, 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"});

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

New features of ES6-make the difference between front and back smaller

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.