Learn about the latest javascript standard ES6, javascriptes6

Source: Internet
Author: User
Tags export class

Learn about the latest javascript standard ES6, javascriptes6

ES6 has not been released yet, but it has already used ES6 to rewrite the program. You can believe that various ES789 proposals have already started. The trend is not something that I can catch up.

Although the trend is too fast, we will not keep learning the pace and will not be left behind by the trend. Let's take a look at the new features of ES6, a new generation of JS.

Arrow Operators

If you use C # or Java, you must know the lambda expression. The newly added arrow operator => In ES6 is similar. It simplifies the writing of functions. The left side of the operator is the input parameter, while the right side is the operation and the returned value Inputs => outputs.

We know that callback is a regular event in JS, And the callback usually appears in the form of an anonymous function. It is very complicated to write a function every time. When the arrow operator is introduced, callback can be easily written. See the following example.

Var array = [1, 2, 3]; // a traditional array. forEach (function (v, I, a) {console. log (v) ;}); // ES6array. forEach (v => console. log (v ));

You can open the traceur online code translation page mentioned at the beginning of the article and enter the code to view the effect.

Class Support

ES6 adds support for the class and introduces the class keyword (in fact, the class is always a reserved word in JavaScript, so that it may be used in future versions, now it is useful ). JS itself is object-oriented. The classes provided in ES6 are actually packaged in the JS prototype mode. Now with native class support, the object creation and inheritance are more intuitive, and the calling, instantiation, static methods and constructors of the parent class method are more visualized.

The following code shows how to use the class in es6. Again, you can paste the code to traceur to view the running result.

// Class definition class Animal {// ES6 constructor (name) {this. name = name;} // instance method sayName () {console. log ('My name is '+ this. name) ;}/// class inheritance class Programmer extends Animal {constructor (name) {// directly call 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 'wayou. program (); // output 'I'm coding...'

Enhanced object literal volume

The object literal volume is enhanced, and the writing method is more concise and flexible. At the same time, more things can be done when defining the object. The specific performance is as follows:

  • You can define a prototype in the object literal volume.
  • Function keywords are not required for defining methods.
  • Directly call the parent class Method

In this way, the object literal volume is more consistent with the class concept mentioned above, making it easier and easier to compile object-oriented JavaScript.

// Create the object var human = {breathe () {console. log ('breathing... ') ;}}; var worker ={_ _ proto __: human, // set the prototype of this object to human, which is equivalent to inheriting human company: 'freelancer', work () {console. log ('Working... ') ;}}; human. breathe (); // output 'breathing... '// call the inherited breathe worker method. breathe (); // output 'breathing...'

String Template

The string template is relatively easy to understand. ES6 allows the use of backquotes to create a string. The string created in this method can contain the variable $ {vraible} wrapped by the dollar sign and curly brackets }. If you have used backend strong language such as C #, this function should not be unfamiliar.

// Generate a random number var num = Math. random (); // output the number to leleconsole. log ('your num is $ {num }');

Deconstruct

Automatically parses values in arrays or objects. For example, if a function returns multiple values, the common practice is to return an object and return each value as a property of the object. However, in ES6, the deconstruct feature can directly return an array, and the values in the array will be automatically parsed to the corresponding variable that receives the value.

Var [x, y] = getVal (), // deconstruct of function return values [name, age] = ['wayou ', 'male', 'secret']; // array deconstruct function getVal () {return [1, 2];} console. log ('x: '+ x +', y: '+ y); // output: x: 1, y: 2 console. log ('name: '+ name +', age: '+ age); // output: name: wayou, age: secrect

Default Value of the parameter. It is optional. Extended parameter.

1. default parameter value

Now you can specify the default value of a parameter when defining a function, instead of using logic or operators as before.

Function sayHello (name) {// the traditional method of specifying default parameters var name = name | 'dude'; console. log ('hello' + name);} // use the default function sayHello2 (name = 'dude') of ES6 {console. log ('Hello $ {name} ');} sayHello (); // output: Hello dudesayHello ('wayou'); // output: Hello WayousayHello2 (); // output: Hello dudesayHello2 ('wayou '); // output: Hello Wayou

2. Indefinite Parameters

An undefined parameter is an undefined parameter that is received by using a named parameter in a function. This is just a syntactic sugar. In the previous JavaScript code, we can use the arguments variable to achieve this purpose. The format of an indefinite parameter is three periods followed by variable names that represent all indefinite parameters. For example, in the following example ,... X represents all parameters passed into the add function.

// Add function (... x) {return x. reduce (m, n) => m + n);} // pass the console of any number of parameters. log (add (1, 2, 3); // output: 6console. log (add (1, 2, 3, 4, 5); // output: 15

3. Extended Parameters

Extended parameters are in another form of syntax sugar, which allows passing arrays or arrays of classes as function parameters without applying.

Var people = ['wayou ', 'john', 'sherlock']; // The sayHello function was originally used to receive three independent parameter demon functions: Role le1, role 2, and role 3, lele2, people3) {console. log ('Hello $ {people1}, $ {people2}, $ {people3} ');} // However, we pass an array as an extended parameter, it maps well to each individual parameter sayHello (... people); // output: Hello Wayou, John, Sherlock // In the past, if you need to pass an array as a parameter, we need to use the apply method of the function sayHello. apply (null, people); // output: Hello Wayou, John, Sherlock

Let and const keywords

Let can be regarded as var, but the variables defined by it can only be used within a specific range, and leaving this range is invalid. Const is intuitive and used to define constants, that is, variables that cannot be changed.

For (let I = 0; I <2; I ++) console. log (I); // output: 0, 1 Console. log (I); // output: undefined. An error is returned in strict mode.

For of value Traversal

We all know that the for in loop is used to traverse arrays, class arrays or objects. The for of loop function introduced in ES6 is similar. The difference is that each loop provides a value instead of a serial number.

Var someArray = ["a", "B", "c"]; for (v of someArray) {console. log (v); // output a, B, c}

Note that this feature is not implemented by google traceur, so debugging cannot be simulated. The same is true for some of the following features:

Iterator, generator

This part of the content is a bit cool. For details, refer to here. The following are some basic concepts.

  • Iterator: it is such an object and has a next method. This method returns an object {done, value}. This object contains two attributes, a Boolean done and any value.
  • Iterable: This is an object with an obj [@ iterator] method. This method returns an iterator
  • Generator: It is a special iterator. The next method can receive a parameter and the returned value depends on its constructor function ). Generator also has a throw method.
  • Generator function: the constructor of generator. The yield keyword can be used in this function. Where yield appears, values can be passed to the outside world through the next or throw method of generator. The generator function is declared through function *.
  • Yield Keyword: It can pause the execution of the function, and then enter the function to continue execution.

Module

In the ES6 standard, JavaScript supports module native. This modular concept of splitting JavaScript code into small pieces of different functions is popular in some third-party specifications, such as the CommonJS and AMD models.

Write codes of different functions in different files. Each module only needs to export the public interface, and then the module can be imported elsewhere. The following example is from tutsplus:

// Point. jsmodule "point" {export class Point {constructor (x, y) {public x = x; public y = y ;}}// myapp. js // declare the referenced module point from "/point. js "; // it can be seen that although the referenced module is declared, you can still import the import Point from" point "by specifying the required part; var origin = new Point (0, 0); console. log (origin );

Map, Set, WeakMap, and WeakSet

These are newly added set types, which provide more convenient methods to obtain attribute values. You do not need to use hasOwnProperty as before to check whether an attribute belongs to the prototype chain or the current object. In addition, the get and set methods are used to add and obtain attribute values.

The code below is from es6feature

// Setsvar s = new Set();s.add("hello").add("goodbye").add("hello");s.size === 2;s.has("hello") === true;// Mapsvar m = new Map();m.set("hello", 42);m.set(s, 34);m.get(s) == 34;

Sometimes we use an object as the key of an object to store property values. Common set types such as simple objects will prevent the garbage collector from recycling these objects that exist as property keys, there is a risk of Memory leakage. WeakMap and WeakSet are more secure. If no other variables reference these objects as attribute keys, they will be recycled and released. For more information, see the following example.

Body code from es6feature

// Weak Mapsvar wm = new WeakMap (); wm. set (s, {extra: 42}); wm. size = undefined // Weak Setsvar ws = new WeakSet (); ws. add ({data: 42}); // because the temporary object added to ws references it without other variables, ws will not save its value, that is, this addition is meaningless.

Proxies

The Proxy can listen to what happened to the object and perform corresponding operations after these events occur. All of a sudden, we have a strong tracking capability for an object, and it is also very useful in data binding.

The following example is used here.

// Define the target object var engineer = {name: 'Joe sixpackage', salary: 50}; // define the handler var interceptor = {set: function (handler er, property, value) {console. log (property, 'is changed to', value); consumer er [property] = value ;}}; // create a Proxy to listen on engineer = Proxy (engineer, interceptor ); // make some changes to trigger the agent engineer. salary = 60; // console output: salary is changed to 60

I have added comments to the above Code, which will be further explained here. After a corresponding event occurs on the listened object, the method in the processing program is called. In the preceding example, we set the set processing function, which indicates that, if the property of the object we listen on is changed, that is, set, the handler will be called and the parameter can be used to know which property is changed, to which value.

Symbols

We know that the object is actually a set of key-value pairs, and the key is usually a string. In addition to strings, we can also use the value of symbol as the key of the object. Symbol is a basic type, like a number, a string, and a Boolean. It is not an object. The Symbol is generated by calling the symbol function. It receives an optional name parameter, and the return value of this function is unique. Then you can use this return value as the key of the object. Symbol can also be used to create private attributes. external users cannot directly access the attribute values that are used as keys.

The following example is from es6features.

(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 // unable to access this attribute because it is private

Math, Number, String, and Object APIs

Many new APIs are added for Math, Number, String, and Object. The following code is also from es6features, which provides a simple demonstration of these new APIs.

Number.EPSILONNumber.isInteger(Infinity) // falseNumber.isNaN("NaN") // falseMath.acosh(3) // 1.762747174039086Math.hypot(3, 4) // 5Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 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: new Point(0,0) })

Promises

Promises is a mode for processing asynchronous operations. It was previously implemented in many third-party libraries, such as jQuery's deferred object. When you initiate an asynchronous request and bind it to Event Handlers such as. when () and. done (), the promise mode is actually applied.

// Create promisevar promise = new Promise (function (resolve, reject) {// perform some asynchronous or time-consuming operations if (/* if successful */) {resolve ("Stuff worked! ") ;}Else {reject (Error (" It broke ") ;}}); // bind the handler promise. then (function (result) {// If promise is successful, the console is executed here. log (result); // "Stuff worked! "}, Function (err) {// If promise fails, console. log (err); // Error:" It broke "}) will be executed here "});

In summary, the difference between the frontend and backend is getting smaller and smaller. Based on lukehoban/es6features, this article also references a large number of blog materials, the purpose of doing so many homework is to help you better understand the latest javascript standard ECMAScript 6 and hope to help you learn it.

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.